- Home /
Setting an object reference to null
I have a reference to a gameObject. At the start of the game it is null - during the game it is assigned to different gameObjects as needed. I wan to be able to test if it is null or set to whatever gameObject. The problem is I get an error 'Object reference not set to an instance of an object' when it is null. Why cant I have a null object reference?
Are you testing GameObjects , just in case it is not null ?
GameObject obj = null;
if(obj != null){ //here you test with other Game Object }else{ //here you already know that the Game object is null }
As @SamuZen implies through code suggestions and also from your error message, it seems you are accidentally still calling methods of an object, set to null at the time, which as you know is not permitted. For sanity check and confirmation, yes you can have objects set to null.
You get the error message if it's null, because the game will try to do something to something that isn't there. It's not intelligent, if you don't tell it to check first, it won't check. Look at SamuZen's code, it's the right way of doing it.
Answer by bubzy · Oct 29, 2014 at 10:47 AM
as mentioned in the comments you can run an if
statement or you can do something like the example below
GameObject tempGO = new GameObject();
GameObject yourGO = new GameObject();
void Start()
{
tempGO.tag = "tempGO"; //in case you need to check the gameobject by tag
}
void Update()
{
//assign your gameobject here
//when you unassign it you can use
yourGo = tempGo;
//this way the gameObject will never be null
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613170226im_/https://answers.unity.com/themes/thub/images/avi.jpg)