Skip to main content

Posts

Showing posts with the label 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