- Home /
Why do I have to re-add my Script on every Unity start?
Hi there,
I have an GameObject GUI. To this GO I added tw scripts: Handler and Creator.
Handler contains an multidimensional array, which is initialized in Awake(). Creator fetches Handler via GetComponent in Awake and "stores" this array into a private variable. This variable is accessed 2 times in this code. And it all works fine....
... until I close Unity. When I start it again and try to run the code, a NullReferenceException will occur at the place where I use the array mentioned above.
When I now go to GUI, remove Handler and add it again everything is fine.
But I have to do this EVERY SINGLE TIME...
Anyone got a clue what this could be? Or better, how to fix it?
Answer by keinabel · Jan 29, 2013 at 11:36 PM
Because of this, you should use Awake to set up references between scripts, and use Start to pass any information back and forth. - Unity Script Reference
The problem was caused by trying to access the array in Creators Awake(). The reference to Handler might be set in Awake(), but fetching the array at this point will cause this NullReferenceException.
I moved the getArray() call to Start() and now it works fine.
Right, Awake is called immediately when the class get created initialized. Since Unity will create all objects one by one it can happen that when your Creator instance is created the Handler instance hasn't been created yet.
Start on the other hand is called when the whole scene is loaded. It will be called when the first frame starts, right before the first Update. At this point it's safe to access other objects.
Answer by schaddemm · Jan 29, 2013 at 11:38 PM
def not normal.
It might be a bug in the unity libs (the way has the links between assets setup). I think RebuildAllAssets could fix that. Also, just in case, Save the scene after making your change. Also, check that the modification to your GUI-gameobject is applied to your prefab. (click apply in the inspector)
Other thing I could imagine is that its something script related, bad initialization code.
Just reread your post, sounds like bad initialization code. Do you have the link=GetComponent() in Start or Awake? Maybe you're accessing the component before it's been created, which would explain the nullreference.
It was bad initialization. I'm still quite the unity newby.