Property not set in inspector, prints null but doesn't == null

I have a property in a MonoBehavior, defined in the following way:

public GameObject whatever = null;

I set it to an actual GameObject reference on some of them, leave it blank in others. Basically, its an optional property. Now, the craziest thing happens when I test it in the program:

Debug.Log(whatever + " " + (whatever == null));

This prints: “null False”. I have no idea how to proceed. All I want is to be able to null test it in code.

The following Test Behavior exhibits this issue and requires no further code:

using UnityEngine;
using System.Collections;

public class TestBehavior : MonoBehaviour
{
    public GameObject whatever;

	// Use this for initialization
	void Start ()
	{
	   Print(whatever);
	}
	
	public void Print<T>(T anObject)
	{
	   Debug.Log(anObject + " " + (anObject == null));
	}
}

It looks like you’ve fallen victim to this. Pay specific attention to the second and third answers and kind of ignore the first.

For what you’ve got at the moment, EqualityComparer from System.Collections.Generic would do the trick.

EqualityComparer.Default.Equals(anObject, default(T))

It is worth examining whether your use case really warrants the use of unconstrained generics, though. The problem in this case is that the compiler cannot know whether T is nullable or not, it could well have been a value type.

I don’t know if it would fit your specific use case, but constraining it to types derived from UnityEngine.Object might or might not be enough.

Yes I tried that, didn’t make a difference.