- Home /
Affect every object in array.
Hello. What I'm trying to do is disable all the lights i have selected in the Inspector, but since the number of lights may vary i can't use: [0], [1], [2] etc. I guess i have to use [Lights.length] but i get the error "Array index is out of range." when i run it maybe cause i haven't set the min of the array. Here is a part of my script if that helps.
var LightSources : Light[];
function Update ()
{
LightSources[LightSources.length].GetComponent.<Light>().enabled = false;
}
Answer by Cherno · Oct 23, 2015 at 06:26 PM
Loop through the array like this:
foreach(Light light in LightSources) {
light.enabled = false;
}
or
for(int i = 0; i < LightSources.Length; i++) {
Light light = LightSources[i];
light.enabled = false;
}
As for your error: Note that you try to access the elements at position (LightSources.Length). If LightSources.Length is, say, 5, then you try to access the element. as position 5 However, with a Length of 5, the element positions are 0,1,2,3,4, so 5 is outside the scope of the array. In any way, this would only affect this one element in the array, not all of them as you might have thought.
I'm not sure i need a loop for what i want to do. I just want to disable all the lights that's all. Ins$$anonymous$$d of using LightSources[0].GetComponent.<Light>().enabled = false;
i want to use a line that will disable them all at once. Since i can't use LightSources[0, LightSources.length].GetComponent.<Light>().enabled = false;
there must be something similar.
A loop is the means of making changes to multiple objects at once.
@Cherno has it right. You already have your array, so you simply need to change each object in the array.
That said, even if there were a function to modify all elements in an array simultaneously, on the backend, it would still have to go one-by-one, so it would have an identical computational cost.
Edit: Additionally, you can have an array of Lights to populate coinciding with your lightsources. For example:
private var Light[] lights;
function Start()
{
for(var i = 0; i < LightSources.length; i++)
{
lights[i] = LightSources[i].GetComponent(Light);
}
}
Then, in your Update() function, you can turn off the "lights" rather than getting the components back out of the "LightSources" every time.
I don't really recommend it, as a simple loop would be more readable and more efficient, but this fits your one line requirement
using System.Linq
LightSources.ForEach(light => light.enabled = false);
still just a loop on the backend
Ahhh, I see now. It's working fine. I though it would be much easier, something to do with length but i guess i was wrong. Cheers guys !