Object is null and not null at the same time

i have this very simple if statement that acts very weird:

public Text ammoText;     // Is assigned through the inspector

void SetAmmoText(){    // called on update

    string ammoCount = "10";  // is constant for testing
    if(ammoText == null)
         Debug.Log("Ammo text is null");
    else{
        Debug.Log("Changing ammoText");
        ammoText.text = ammoCount;
     }
}

The Text object is assigned through the inspector and is there in runtime, the weird thing is that both Debug messages appear in the console without any errors.

If i write this:

void SetAmmoText(){    // called on update

    string ammoCount = "10";  // is constant for testing
    ammoText.text = ammoCount;
}

the code works (the text is changed) but i get a null reference exeption for the text object.

Thanks in advance.

Where are you calling SetAmmoText from? Is there any other place where you might be setting ammoText to null?

Maybe you have two of the components in your scene. one with a Text object assigned, one which doesn’t have one…

Edit: you can find out by typing into the search field of the hierarchy t:MyComponentType

2 Likes

only in the update method of that script

That was it. For some reason i had the script at two places, so the if statement was called twice, but on one of the scripts the text object was null (so the first debug message was printed) and the other script had the text object (so the second debug message was printed)