Reputation: 2069
In Unity, GameObject can be destroyed.
Here's the scenario:
From here everything is happy. We can do anything with GameObjectB.
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
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