MonoBehaviour Startup Interdependency

From Schmid.wiki
Jump to: navigation, search

Oftentimes, a MonoBehaviour is dependent on another MonoBehaviour being started. If the behaviour that should be started first is a singleton, the following design pattern with a idempotent Start method can be employed:

public class Dependent : MonoBehaviour {

    /**
     * @note Depends upon a Something being in the scene.
     */
    public void Start() {
        if(Something.Instance == null)
            // handle error
        else
            Something.Instance.Start();
    }
}

/**
 * @note Singleton.
 */
public class Something : MonoBehaviour {

    /**
     * @note May not be started earlier than in a Start()-method.
     * @note Idempotent.
     */
    public void Start() {
        if(! started) {
            started = true;

            // do stuff
	}
    }
    bool started = false; // Idempotence of Start()

    // Singleton =================================================
    static Something instance = null;

    // Set instance here because Awake gets called whether the
    // script is enabled or not.
    void OnEnable() { instance = this; }
    
    /** If a Something is in loaded scene, Instance is
     * guaranteed to be non-null in any Start()-method.
     */
    public Something Instance {
        get { return instance; }
    }
}
Personal tools