The Script I Put on an empty GameObject is
using UnityEngine;
using System.Collections;
public class NULLTEST : MonoBehaviour {
// Use this for initialization
void Start () {
TestClass classVar = new TestClass();
Debug.Log("Is ClassVar null = " + (classVar == null));
if (classVar)
{
Debug.Log(“ClassVar is null”);
}
else
{
Debug.Log(“ClassVar is not null”);
}
}
// Update is called once per frame
void Update () {
}
}
The TestClass is
using UnityEngine;
using System.Collections;
public class TestClass : UnityEngine.Object
{
}
The OutPut is :
Is ClassVar null = True // TRUE?
if the TestClass is extended from System.Object ,It works ok(standard c# libraries work well),Is this a bug?
BTW,if I set
TestClass classVar = null;
it will output :
Is ClassVar null = True
ClassVar is not null // OMG…
no,my problem is that I don’t have a way to check if the objects from UnityEngine.Object is null or not…
your class derived from UnityEngine.Object will be always null. Im facing the same problem.
I know this thread is super old… but the reason UnityEngine.Object subclasses return null is because of Unity’s silly operator overloading stuff. The objects aren’t really null. Unity overrides the “==”, “!=”, and “bool” operators so that the objects return null even though they actually aren’t.
This is because they use their own Instantiate and Destroy methods, so once an object has been instantiated, it acts non-null, and once it’s destroyed, it acts like it’s null.
I haven’t figured out an ideal workaround for this yet, but it’s worth noting that all the methods, variables, and properties of these “null” objects still work fine.
1 Like
Actually I think I just figured out a solution for this by overriding a few things:
public class FixedObject : UnityEngine.Object
{
public static implicit operator bool(FixedObject thing)
{
return !System.Object.ReferenceEquals(thing, null);
}
public static bool operator == (FixedObject a,FixedObject b)
{
return System.Object.ReferenceEquals(a, b);
}
public static bool operator != (FixedObject a,FixedObject b)
{
return !System.Object.ReferenceEquals(a, b);
}
public override bool Equals(object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return this.GetInstanceID();
}
public override string ToString()
{
return name;
}
}
Out of curiosity, what’s the point in doing that at all? Why not either use a standard class or inherit from ScriptableObject?