GetComponent returning "null" instead of null

Viewed 1511

I'm confused about the return value of GetComponent if the requested component is not attached to the object. According to the Unity documentation, GetComponent should return null. However, what appears to be happening is that GetComponent is returning a "null" object of the requested type, rather than the value null.

In this example, my game object does not have a CircleCollider2D attached to it. When I set a breakpoint on the line CircleCollider2D x = GetComponent<CircleCollider2D>();, I get this result

Why is the returned value not null?

EDIT:

Here's a full screenshot of the code and the values in the debugger.

ANOTHER EDIT:

Could it be that Unity has overloaded the == operator so that GetComponent always returns a object, but the object can have an internal "null" state which returns true when compared to null? I can see the following declarations in the UnityEngine namespace

public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);
4 Answers

if you are still looking for solution this worked for me`

var component = parent.GetChild(i).GetComponent<T>();
if(component != null)
{
    if (component.ToString().Equals("null") == false)
    {
        list.Add(component);
    }
}
Related