error Guides NullReferenceException Object

NullReferenceException: Object reference not set to an instance of an object

Nabeel
August 28, 2016
0 Comments
Home
error
Guides
NullReferenceException
Object
NullReferenceException: Object reference not set to an instance of an object


NullReferenceException: Object reference not set to an instance of an object

This Exception occurs in Unity whenever you try to access a variable that is not initialized or does not refer to any object. For example when you create a GameObject variable in a script, by default it does not refer to anything. To assign a value to that GameObject variable you have to make it equal to some value before using it.

Example:


<?phpPublic GameObject myObject;
void Awake(){
 myObject = someObject;
}


You can either set myObject in code as shownin example above, or through inspector as it is a public object (refer to image below).


This exception can also occur while trying to instantiate and object for same reason. For Example:

Instantiate(myObject,new Vector3.zero,Quaternion.Identity);

This might give NullReferenceException if myObject variable refers to nothing.
This Exception will also occur if you are trying to access a member function of uninitialized object. For Example:


Private GameObject myObject;
Void SomeFunction(){
Print(myObject.name);
}

This would give NullReferenceException as we are trying to access name of an uninitialized GameObject. To correct this error we should equate the variable to some object before using it.

Answer by Muhammad Ahmed

Blog authors

No comments