kitta
kitta

Reputation: 2069

How Unity make GameObject instance destroyed while it is referenced?

In Unity, GameObject can be destroyed.

Here's the scenario:

  1. Instantiate GameObjectA and GameObjectB
  2. Add a script to GameObjectA (this script can hold reference of another GameObject)
  3. Script in GameObjectA find and hold the reference of GameObjectB.

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

  1. 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#?

Upvotes: 4

Views: 618

Answers (1)

David Oliver
David Oliver

Reputation: 2321

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.

Upvotes: 5

Related Questions