Null Reference Exception when trying to refer to a public variable.

In a script called “Gun Interaction”
There is a public variable called “Gun Tip”…
Before I made the variable public I made it a serialize Field and set a game object to it.
Which as you can see in the Inspector window still exists after setting it to Public.
I printed the name of the Gun Tip in the Gun Interaction Script it returned “Tip”
But when printing the name of the Gun Tip in Movement script it returned a Null Reference Exception.
I have no idea why the Movement script is unable to access the value of my public variable even though I can reference it. Any Ideas on how to fix?



Use [SerializedField] only on private variables that you want to show up in the inspector but you don’t want to access from other classes. If you need to access them from other classes as well then make it public, but not serializable, since they’re by default serialized.

I’m a bit confused of what you’re trying to achieve, but that might be an execution order issue: the Movement Start function is called before the Gun interaction one. Always initialize your objects in the Awake function, then do your connection between objects in the Start function.

Where did you initialize your private variable GunInteraction in your Movement script? That’s null.

I was just using the start function as an example, the real script is a bit more complicated but it will only refer to the public variable if the character moves left. The same error occurs, so it is not an execution order issue.

the variable looks like this:

public Gun Tip;
//Without the space in between

Is it that I cannot use a public variable the same as i can a serialized one? Where I can assign the game Object into a slot in the Inspector, does that not work for public?