- Home /
Getting a NullReferenceException when trying to assign a script variable
I'm trying to assign a script as a variable so I can easily access variables within this script. I've done this before, but for some reason in this specific instance it's constantly throwing errors when I try to use the assignment, as if it's unable to find the script I'm referencing.
I'll post my initialisation code here, even though I was still getting this trouble when I just dragged and dropped the component into the relevant variable slot in the Unity window.
public var player: GameObject;
public var x: int;
public var y: int;
private var found: boolean;
var board: GameObject;
var mainCode: StuffHolder;
mainCode = FindObjectOfType(StuffHolder);
private var size: int = mainCode.size;
So I am 99% sure I didn't screw this up in code and I'm asking... what other ways could I have screwed this up?
$$anonymous$$oments after posting this I find out that by having the actual initialisation happen within the Awake function it runs smoothly. $$anonymous$$y guess is that initialisation on the other script took so long that it wasn't finished in time for this script? That's my vague guess, someone more knowledgeable might correct this for posterity.
in that case you could mess around with the script execution order in the project settings give your StuffHolder higher priority than the class that is accessing StuffHolder.
or you can simply move the initialization part into different init functions, since they run in different order, as stated here
Answer by MiniFish · Jan 02, 2015 at 03:36 AM
mainCode = FindObjectOfType(StuffHolder);
private var size: int = mainCode.size;
i think you should put these two into one of those initialization functions, like Start() and the like.
otherwise, assuming that your StuffHolder class have a variable called size, it might be that the variable is not initialized and you're trying to access it, causing it to throw null reference exceptions.
Yeah, Start didn't work but Awake did, for whatever reason. I commented on the original question with my best guess why but the important thing is that it's working.
Your answer
![](https://koobas.hobune.stream/wayback/20220613175403im_/https://answers.unity.com/themes/thub/images/avi.jpg)