Mount this script to object A and another script assigns TestClass via Init(). When object A is destroyed by the Destroy() method, do I need to release the TestClass reference in OnDestroy()?
Again, I don’t need to empty TestClass. I remember I need to empty a reference when the reference type is not in use.
Generally you don’t need to do the above but you can if you want to be thorough.
You should avoid using OnDestroy() for many different reasons related to lifetime.
You should use OnEnable / OnDisable for set / clear type stuff like this, or for sub / unsub
public static MyClass Instance { get; private set; }
void OnEnable()
{
Instance = this;
}
void OnDisable()
{
Instance = null; // keep everybody honest when we're not around
}
Anyone can get at it via MyClass.Instance., but only while it exists.
In C# stuff will generally get garbage-collected when all references are gone. This is a separate process from the actual underlying engine object(s) if any getting destroyed.
For future reference:
If you post a code snippet, ALWAYS USE CODE TAGS:
How to use code tags: Using code tags properly
- Do not TALK about code without posting it.
- Do NOT post unformatted code.
- Do NOT retype code. Use copy/paste properly using code tags.
- Do NOT post screenshots of code.
- Do NOT post photographs of code.
- Do NOT attach entire scripts to your post.
- ONLY post the relevant code, and then refer to it in your discussion.
Thanks for your help!
Technically you don’t need to do that. When all references to Test will be gone, TestClass will be cleared up with it.
