Skip to content

Instantly share code, notes, and snippets.

@yongkangchen
Created May 14, 2015 09:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongkangchen/2b048c7490733ee050f0 to your computer and use it in GitHub Desktop.
Save yongkangchen/2b048c7490733ee050f0 to your computer and use it in GitHub Desktop.
How does Unity null all references to a GameObject after Object.Destroy is called on it?
using UnityEngine;
public class Main : MonoBehaviour {
void Start ()
{
FakeObject obj = new FakeObject ();
Debug.LogError (obj); // [FakeObject]
Debug.LogError (obj == null); // false
Debug.LogError (obj.num); //100
FakeObject.DestroyImmediate (obj);
Debug.LogError (obj); // null
Debug.LogError (obj == null);//true
Debug.LogError (obj.num); //100
}
}
class FakeObject
{
public int num = 100;
private bool destroyed = false;
public static void DestroyImmediate(FakeObject obj)
{
obj.destroyed = true;
}
public override string ToString ()
{
if (destroyed)
{
return "null";
}
return string.Format ("[FakeObject]");
}
private static bool CompareBaseObjects (FakeObject x, FakeObject y)
{
if ((object)x != null && x.destroyed) {
x = null;
}
if ((object)y != null && y.destroyed) {
y = null;
}
return object.Equals (x, y);
}
public static bool operator == (FakeObject x, FakeObject y)
{
return CompareBaseObjects (x, y);
}
public static bool operator != (FakeObject x, FakeObject y)
{
return !CompareBaseObjects (x, y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment