- Home /
Accessing lights from c# code
Hello I have a scene setup, with five point lights named pl1, pl2...pl5. Now I am very new to Unity, and I would like that when the game starts I want the intensity of the point lights to be 0, and whenever the player controller gets a certain amount of distance from the light it would increase its' intensity.
Now I understand I have to do this: I created an empty game object which I named gameController, created a c# script, and in it I need to instantiate a Light array, and in the start method to set their intensity to zero, and just go on coding the change of intensity in the update method.
What I am having trouble with is how on earth do I access the lights in my code? I searched many posts and I couldn't find one straight answer.
I tried: Light[] lights = (Light)FindObjectsOfType(typeof(Light)); That doesn't work.
now I thought about creating a GameObject array, but then, how do I make sure it returns a light?
I would very much appreciate any help.
Thank you.
Answer by TK5005 · Jul 25, 2013 at 04:01 PM
private Light[] lights;
// Use this for initialization
void Start () {
lights = FindObjectsOfType(typeof(Light)) as Light[];
foreach(Light light in lights)
{
light.intensity = 0;
Debug.Log(light);
}
}
This would give you a list of all of the Lights in the game. If there are other lights, using FindWithTag() would be better.
Answer by wolfadex · Jul 25, 2013 at 03:55 PM
GameObject.light will give you access to the light.
For finding the GameObjects with lights, you could use GameObject.FindWithTag() and make sure your lights are tagged with something like 'light' or 'dimmingLight'.
Answer by sundayhd5 · Apr 23, 2020 at 12:17 AM
Light is a GameObject with a "Light" compoment. Therefore, you can find any light the same way you that you find GameObjects, Then you can get the light compoment from them and change light properties. For example:
Light myLight = GameObject.Find("MyLight").GetComponent<Light>();
// now we can change light properties...
myLight.range = 5;
myLight.intensity = 2;
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
gameObject are not referenced 2 Answers
Ordering a list of GameObjects 3 Answers