The lifespan of an object instance in a Monobehavior script
A MonoBehavior script ReferenceAgent.cs has a instance of non-MonoBehavior class ReferenceObject. ReferenceObject.cs has a random string attribute which is for testing purpose.
Now we have a MonoBehaivor script Test.cs, which has references of ReferenceAgent component and its ReferenceObject instance.
If I destroy the GameObject - the one ReferenceAgent attached - in Test.cs, I can't visit the reference of ReferenceAgent anymore, but I can still visit the reference of ReferenceObject which should be an attribute in ReferenceAgent.
Is this a stable feature or just because I'm visiting the attribute which causing the program keep the instance in memory?
public class ReferenceAgent : MonoBehaviour {
private ReferenceObject refObject;
public ReferenceObject RefObject
{
get { return refObject; }
}
// Use this for initialization
void Awake () {
refObject = new ReferenceObject(Random.Range(100, 999).ToString());
}
}
============================================================
public class ReferenceObject {
private string testObjName;
public string TestObjName
{
get { return testObjName; }
}
public ReferenceObject(string name)
{
this.testObjName = name;
}
}
============================================================
public class Test : MonoBehaviour {
public ReferenceAgent agent;
public ReferenceObject refObject;
// Use this for initialization
void Start () {
refObject = agent.RefObject;
}
void Update() {
if(Input.GetKeyDown(KeyCode.Q))
{
Debug.Log(refObject.TestObjName); // This will work after pressing key W
Debug.Log(agent);
}
if(Input.GetKeyDown(KeyCode.W))
{
Destroy(agent.gameObject);
}
}
}