- Home /
Would setting this static cause a memory leak?
My friend's script has a static instance to itself. We had a debate and I wasn't sure later. My question: Would setting this static in a Awake/Start cause a memory leak when the scene gets reloaded?
public class ExClass : MonoBehaviour {
private static ExClass instance;
public static ExClass Instance {
get { return instance; }
}
private void Awake() {
instance = this;
}
//...
}
Answer by CHPedersen · Aug 01, 2012 at 11:36 AM
No. :) If the scene gets reloaded, then a new instantiation of this script will be made when a fresh copy of whatever object it is attached to is loaded during scene load. This causes the Awake method to fire again, but this doesn't create another copy of the static ExClass reference, only a fresh copy of the actual MonoBehavior it points to. The old copy that the static variable pointed to was destroyed along with the object it was attached to when Unity left that scene upon reloading.
In summary: What you're seeing above is just a way of making a script reference statically available so you can access it through ExClass.instance instead of having to go through GameObject.Find([Gameobject_name]).GetComponent()
to get a reference to it. This is generally fine, but only if this particular script is attached to only one gameobject and only once to that gameobject.. If not, the static reference gets set to whatever instance of this script happens to load last, which is arbitrary.
I really hate that Unity Answers tries to avoid script injection by disallowing the greater-than / less-than characters. Does anyone know how to get around that so I can properly denote use of generics?
Oh I see. Thanks for the clear answer, it makes sense now.
Glad it made sense. :) Could I get you to please mark the answer accepted?
yeah I've figured that out
< space "stuff you need to write" space >
if you do without spaces it eats what ever is between this 2