[Unity C#] Single Instance

When there should be only one instance of this class in the whole game that shouldn’t be destroyed.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CS_MessageBox : MonoBehaviour {

    private static CS_MessageBox instance = null;

    //========================================================================
    public static CS_MessageBox Instance {
        get { 
            return instance;
        }
    }

    void Awake () {
        if (instance != null && instance != this) {
            Destroy(this.gameObject);
        } else {
            instance = this;
        }
        DontDestroyOnLoad(this.gameObject);
    }
    //========================================================================

    public void FunctionYouNeed () {
        Debug.Log("FunctionYouNeed is called :)");
    }
}

To call this instance

CS_MessageBox.Instance.FunctionYouNeed();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s