Public variables null after assigned in the inspector.

I have this scrap of code:

`public Texture2D myBackgroundImage;

void OnGUI() {

if (!myBackgroundImage) {

Debug.LogError("myBackgroundImage is null");

}

` //end scrap

The public Texture2D allows my to assign a graphic image to the variable via the inspector. I do this but when I run the code the LogError stops the program and shows the 'is null' message.

I had it working before but tried to add a graphic to a button. After that all of my public variables are null even though they show assigned in the inspector (even after removing the button image reference.

The ! operator never worked for me like that, try

if( myBackgroundImage == null )

But since you can start your game this might not be the error, otherwise there is nothing wrong in the information you provide. Are the variables still set in the inspector while you are playing?

The ! exclamation mark is not used to determine if an object is null. It is used to determine if a value is false, and is used on boolean types.

The correct way to determine if an object is null is to use

if(myBackgroundImage == null) 

above as Oliver says.

Thanks for the quick response all. I found that the problem was that I was assigning the public variables (drag and drop style in the inspector) on the script itself (in the project section) rather than the instance of the script (in the hierarchy section). I have this script attached to the main camera and when I assigned the values to the script attached to that game object everything worked the way that I intended. The inspector interface is a bit odd to me as I am not used to assigning variables drag and drop style.

As far as testing for null it is possible to test for null with the negation " ! "

if (!mySkin) {

Debug.ErrorLog("The my_skin object is unassigned.");

}

The variable mySkin is an object and the opposite of an object is not an object (or a null reference). Therefore the test for null with the " ! " operator is valid. In this case when mySkin is not assigned in and the program is executed it stops and throws the ErrorLog message.

Cheers.