LWRP Light 2D change sprite in script

I need to change the sprite of a 2D light in a script. I need to create a Light2D with a light type Sprite and then in the script change the sprite to whatever I need. I looked at the object and all I can see that is is a sprite is lightCookieSprite that is only get-able.

GameObject glowComponent = Instantiate(new GameObject("GlowComponent"));
Light2D light = glowComponent.AddComponent<Light2D>();
light.lightType = Light2D.LightType.Sprite;
light.??? = sprite;

How can I change the sprite like in the inspector?

1 Like

Hi, did you find the way ?

1 Like

Same question.

1 Like

By editing your temporary version of Light2D.cs you can work around this; I’m not sure why it’s not settable, Light2D itself already supports the sprite being changed in other parts of the code from what it seems.

You’ll need to change line 212 to the following:

public Sprite lightCookieSprite
        {
            get { return m_LightCookieSprite;}
            set { m_LightCookieSprite = value; }
        }

I’m not sure how safe or stable this is, but it works decently enough until Unity updates the field to be officially settable.

1 Like

How do you access the Light2D.cs file? I havent been able to find it.
Edit: Nevermind, You just gotta right click the component and hit “Edit script”…

Can Unity please take care of this? This sound trivial to fix but it would save so much pain… fields visible in the inspector should be changeable by code.

yea this work perfectly but i dont know why my script keep reset every time i turn on unity

Have u solved it? I have the same problem every time I open unity it resets

I have the same problem

    private Light2D _light2D;
    private FieldInfo _LightCookieSprite =  typeof( Light2D ).GetField( "m_LightCookieSprite", BindingFlags.NonPublic | BindingFlags.Instance );

    void UpdateCookieSprite(Sprite sprite)
    {
        _LightCookieSprite.SetValue(_light2D, sprite);
    }

You can access the private backing field for the ‘LightCookieSprite’ property and set that. This applies for any other property that doesn’t have a setter.

I really don’t know how that magic is possible but it works !
Thanks !!