Q: How Unity make GameObject instance destroyed while it is referenced? In Unity, GameObject can be destroyed.
Here's the scenario:


*

*Instantiate GameObjectA and GameObjectB

*Add a script to GameObjectA (this script can hold reference of another GameObject)

*Script in GameObjectA find and hold the reference of GameObjectB.


From here everything is happy. We can do anything with GameObjectB.


*Destroy GameObjectB using GameObject.Destroy


Here when we access GameObjectB from GameObjectA's script it will be null.
You can't access any methods, fields and properties because it have been destroyed.

Problem is how they can do that?
If you think about it carefully.
In pure C# object GC will not collect if someone retain the reference of that instance.
I know Unity have their wrapper layers to those object.
But I wonder how it's work? And how to implement it in C#?

A: There's a subtlety here. In your example, if you check GameObject B it will return equals to null. But that's because Unity have overridden the equality operator of UnityEngine.Object. If you actually try to access any of the GameObject's properties or methods, you won't get a NullReferenceException; you'll get an exception from Unity saying that the object has been destroyed. 
In other words, it still exists from the point of view of .NET/Mono's memory management. So to answer your question, 'how to implement it in C#,' the trick is the equality override. But even Unity themselves have had second thoughts about that design choice, so don't try it at home.
