[Light2D] How to get Light2D Component via scripting
I wanna change the Color on a 2D-Light, but i can't seem to figure out how to get the component. Because GetComponent with Light2D isn't reconized as a thing, only Light works. And there is no documentation on 2D-Light yet. So I hope someone knows how to do it.
This is a script stolen from Unity Documentation of Light:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lightFlickerTest : MonoBehaviour
{
// Interpolate light color between two colors back and forth
float duration = 1.0f;
Color color0 = Color.red;
Color color1 = Color.blue;
Light lt;
void Start()
{
//This part isn't working right with 2D Light
lt = GetComponent<Light>();
}
void Update()
{
// set light color
float t = Mathf.PingPong(Time.time, duration) / duration;
lt.color = Color.Lerp(color0, color1, t);
}
}
Answer by Im-ToXeRs · Aug 14, 2019 at 04:24 PM
Someone found a solution for mig on Reddit https://www.reddit.com/r/Unity2D/comments/cq56l6/light2d_how_to_get_light2d_component_via_scripting/
Answer by Franco-Marini · Apr 23, 2020 at 01:04 AM
include one of this at the beggining of the script:
using UnityEngine.Experimental.Rendering.LWRP; //OLD VERSIONS LIKE 2018
using UnityEngine.Experimental.Rendering.Universal; //2019 VERSIONS
thanks you so much! I know that isn't even my post but i was toiling with it kinda long time. And sorry for language mistakes but i'm not english people.
using this solution does not work for me in Unity 2021.3.2f1. Not sure what has changed or why. Kinda sucks because I really need to alter the intensity of the light from another script
Answer by Rylan523 · Jun 04 at 12:48 AM
Not sure if you still need this but, at some point it must have been changed so now you just use what Franco-Marini said, just without the ".Experimental"
using UnityEngine.Rendering.Universal;
at the beginning of your code,
public Light2D (OBJ NAME HERE);
in the MonoBehaviour class, and
(OBJ NAME HERE) = GetComponent<Light2D>();
in the 'Start' or 'Awake' function.
This is how I was able to get it to work with my script:
So the actual problem for me was just really stupid. I had tried both those ways to no avail, however I eventually tried to regenerate the project files, and that made it work automatically. When in doubt and a data type isn't being recognized by the compiler / visual studio, regenerate dem proejct files