Attach TestMono to an empty GameObject, leave the serialized field uov empty and play. The result is not what I expected.
using System;
using UnityEngine;
using Object = UnityEngine.Object;
namespace TestMisc.Scripts
{
[Serializable]
public class Variable<T>
{
[SerializeField] T m_Value;
public T Value => m_Value;
public void LogInsideGenericClass()
{
// Result: Inside generic class: equal to null: False equal to default: True
Debug.Log($"Inside generic class: equal to null: {Value == null} equal to default: {Value as Object == default}");
}
}
[Serializable]
public class UnityObjectVariable : Variable<Object>
{
public void LogInsideSpecializedClass()
{
// Result: Inside specialized class: equal to null: True equal to default: True
Debug.Log($"Inside specialized class: equal to null: {Value == null} equal to default: {Value as Object == default}");
}
}
}
using UnityEngine;
namespace TestMisc.Scripts
{
public class TestMono : MonoBehaviour
{
[SerializeField] UnityObjectVariable uov;
void Start()
{
uov.LogInsideGenericClass();
uov.LogInsideSpecializedClass();
}
}
}
Why null Unity Object is not equal to null inside generic class?
Unity override the
==operator for Unity objects to make them equal to null in cases where the object isn't actually null (for example if it has been destroyed). Operators are not polymorphic; if you cast the object toObjectthen compare it with==it will useObject's==operator, not some "override" from an inheriting class.If you compare using
Equalsit should yield the same result with or without a cast.If you only want to check for truly null references, use
ReferenceEquals.