117
110

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity C# シングルトンパターンの実装

Last updated at Posted at 2014-08-10

C#でのシングルトンパターン

C#でのシングルトンの一例です。
以下のように書く。

using UnityEngine;

public class SampleSingleton {

    private static SampleSingleton mInstance;

    private SampleSingleton () { // Private Constructor

        Debug.Log("Create SampleSingleton instance.");
    }

    public static SampleSingleton Instance {

        get {

            if( mInstance == null ) mInstance = new SampleSingleton();

            return mInstance;
        }
    }

    public int testNum = 10;

    public void setNum ( int num ) {

        testNum = num;
    }
}

使う側

適当なGameObjectに貼り付けておきます。

using UnityEngine;

public class Sample : MonoBehaviour {

    SampleSingleton sample1;
    SampleSingleton sample2;

    void Start () {

        sample1 = SampleSingleton.Instance;
        sample2 = SampleSingleton.Instance;

        if( sample1 == sample2 ) {

            Debug.Log("sample1 == sample2");
        }

        Debug.Log( sample2.testNum ); // 10

        sample1.setNum(100);

        Debug.Log( sample2.testNum ); // 100
    }
}

MonoBehaviourを使いたい(GameObjectにしたい)場合

便利な機能いっぱいのMonoBehaviourを継承したい場合がありますよね。

using UnityEngine;
using System.Collections;

public class SampleSingleton : MonoBehaviour {

    private static SampleSingleton mInstance;

    private SampleSingleton () { // Private Constructor

        Debug.Log("Create SampleSingleton GameObject instance.");
    }

    public static SampleSingleton Instance {

        get {

            if( mInstance == null ) {

                GameObject go = new GameObject("SampleSingleton");
                mInstance = go.AddComponent<SampleSingleton>();
            }

            return mInstance;
        }
    }

    void Start () {

        Debug.Log("Start");
    }

    void Update () {

        Debug.Log("Update");
    }
}

インスタンス化の時に、GameObjectを生成し自身をコンポーネントに追加する。

117
110
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
117
110

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?