Tuesday, March 20, 2012

Unity3D Pro Tip: Singletons

If you're using DontDestroyOnLoad to preserve a game object across levels, you might find that you get duplicated instances of that object when you reload that level. How do you solve this simply?
public class MyComponent : MonoBehaviour {
    static MyComponent _instance;
    void Awake() {
        if(_instance != null) Destroy(gameObject);
        _instance = this;
If you want to reuse this behaviour, make it a base class and inherit from it in any components you need to persist but not multiply!

No comments:

Popular Posts