I seem to have a problem, keep getting a NullReferenceException in a function that is called from a event trigger on a UI Image.
The reference is to a script, I reference it like so -
private var globalVarsScript : GlobalVars;
function Awake()
{
globalVarsScript = GameObject.Find("Controller Global Variables").GetComponent.<GlobalVars>();
}
If I start the game with the GO active I don’t get the error, but if I SetActive() after picking it up I get the error.
I understand the use of OnEnable() for when disabling and enabling GO’s the need to reset and reference things.
I’ve also tried putting the reference to the script in Awake(), OnEnable() and Start() but still get this error, the only way I can seem to stop it is check in the function being called if globalVarsScript is null -
if(!globalVarsScript) globalVarsScript = GameObject.Find("Controller Global Variables").GetComponent.<GlobalVars>();
Awake doesn’t get called on inactive GameObjects until the GameObject is activated. This means that you can call a method on a component before Awake is called.
There are a couple of approaches
Create the object active and call SetActive(false) during Awake.
Use a property to do lazy initialisation the first time it’s called.
Thanks for that, so this means a method on a component will be called before OnEnable() is called to, as this makes sense because its Awake() then OnEnable() …
This I’ll have to go the second way …
Use a property to do lazy initialisation the first time the function is called.
As doing the Awake() way will cause me to many problems.
But what I don’t understand how is the event trigger on a UI Image being called without any interaction ?
The GO is in the scene inactive, then when set to active I get the error, so the event trigger is calling the function when the GO is made active, right ?
So to call a function in a script (that I presume now is running because the GO has been made active) shouldn’t OnEnable() function have come first where I’d put a reference to the script ?