CodeMonkey CodeMonkey - 3 years ago 119
C# Question

Does a Passed Reference Get Lost Upon Destroying its Creator in Unity/C#?

I have an object that creates another object. I pass the created object to some other object then destroy the original. Assuming the object I passed it to keeps its own reference, does destroying the creator also destroy the created object? I think the answer is no, but perhaps there are some caveats?

class MyObject : MonoBehaviour
{
MyObject myObj = new MyObject();

void someFunc()
{
GlobalObj.GiveObject(myObj)
Destroy(gameObject)
}
}

class GlobalObj
{
MyObject obj;

GiveObject(MyObject o)
{
obj = o;
}
}

Answer Source

MyObject is a reference type so whatever Unity does when Destroy is called, it does not remove the object from memory; the reference is still valid.

The Destroy method seems to be just about removing the object from the game. There may be no Dispose involved which means the instance can be used without any issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download