So I’m trying to get my head around null references when calling from another script. In the below image the first method works fine in the first script and I can also call it from the second script but then I get a null reference i.e., firstScript.lg.enabled = false;
So for it to work I have to (seemingly) write it as in the LampOff method. Why if “lg = GetComponent…” works in the first method do I have to point it to the light again in the second method?
In the second method you call Light.GetComponent() which does not make much sense. So probably when you just do “lg.enabled = false” it should work when the component is there. Also it’s advisable to cache “frequently” used components once in Start.
It just depends on what order the methods are called in. You need to assign lg at some point before you use it. If you try to use lg before you assign it, it’s not actually referencing anything, and you will get an error. Rather than assigning it in these methods as you have here, you should just assign it in Awake so you know it’s guaranteed to have been assigned by the time these methods run, and you only need to assign it once. So you can remove the GetComponent calls from these methods.
Thanks all! Very useful, much appreciated!
I did originally assing lg to “Start” but had no luck but I will take this info and redo the script as I’ve clearly gone about it the wrong way.