Created
May 14, 2015 09:49
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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