Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Light2D programatically

Discussion in '2D' started by twinity1, Apr 25, 2021.

  1. twinity1

    twinity1

    Joined:
    Jan 16, 2021
    Posts:
    2
    Hello,

    Is there any way how to setup the Light2D component programmatically? I'm trying to do something like this:

    Code (CSharp):
    1.            
    2.  var light = gameObject.AddComponent<Light2D>();
    3.  
    4. light.lightType = Light2D.LightType.Freeform; // OK
    5. light.overlapOperation = Light2D.OverlapOperation.AlphaBlend; // can't set, 'cause there is no setter
    6. light.shapePath = new[] { ... }; // same - no setter
    7.            
    I could make a prefab with Light2D preconfigured, but that doesn't solve shapePath, because I will need to have a lot of variants. :(
     
    sean244 likes this.
  2. sean244

    sean244

    Joined:
    Nov 4, 2017
    Posts:
    95
    Has anyone found a solution to this yet? I've heard you can use reflection as a workaround. Would it then be possible to make the freeform light act the same way that a linerenderer would?
     
  3. twinity1

    twinity1

    Joined:
    Jan 16, 2021
    Posts:
    2
    I tried to change properties with reflection and it works, but I think it's not the ideal solution.

    Code (CSharp):
    1.             var overlapOperation = light.GetType().GetField("m_OverlapOperation", BindingFlags.Instance | BindingFlags.NonPublic);
    2.             overlapOperation?.SetValue(light, Light2D.OverlapOperation.AlphaBlend);
    3.          
    4.             var shapePath = light.GetType().GetField("m_ShapePath", BindingFlags.Instance | BindingFlags.NonPublic);
    5.             shapePath?.SetValue(light, new []
    6.             {
    7.                 new Vector3(0, 0, 0),
    8.                 new Vector3(0, 1, 0),
    9.                 new Vector3(1, 1, 0),
    10.                 new Vector3(1, 0, 0),
    11.             });
    12.  
    13.    
    14.             light.GetType().GetField("m_Falloff", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(light, 15.0f);
    15.             light.GetType().GetMethod("UpdateMesh", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(light, new object[] {true});