LoginSignup
68
52

More than 5 years have passed since last update.

[Unity]シングルトンを使ってみよう

Last updated at Posted at 2016-11-20

シングルトンとは

シーンに1つしかないスクリプトには,FindとかGetComponentとかしなくても,簡単にアクセスできる!

手順

  1. SingletonMonoBehaviourというスクリプトをコピペ
  2. 対象となるスクリプトをシングルトンにする.
  3. 呼ぶ

1. SingletonMonoBehaviour

  1. SingletonMonoBehaviourという名前でスクリプトを作成
  2. 中のコードをCommand + AとDeleteで消去
  3. 以下のコードをコピペ
using UnityEngine;
using System;

public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour{

    private static T instance;
    public static T Instance
    {
        get{
            if (instance == null) {
                Type t = typeof(T);

                instance = (T)FindObjectOfType (t);
                if (instance == null) {
                    Debug.LogError (t + " をアタッチしているGameObjectはありません");
                }
            }

            return instance;
        }
    }

    virtual protected void Awake(){
        // 他のゲームオブジェクトにアタッチされているか調べる
        // アタッチされている場合は破棄する。
        CheckInstance();
    }

    protected bool CheckInstance(){
        if (instance == null) {
            instance = this as T;
            return true;
        } else if (Instance == this) {
            return true;
        }
        Destroy (this);
        return false;
    }
}

2. 対象となるスクリプトをシングルトンにする.

ここでは,GameManagerというスクリプトをシングルトンにする.

元のスクリプト

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public void Test(){
        Debug.Log ("シングルトン!");
    }
}

編集後

using UnityEngine;
using System.Collections;

public class GameManager : SingletonMonoBehaviour<GameManager> {

    public void Test(){
        Debug.Log ("シングルトン!");
    }
}

MonoBehaviourの部分がSingletonBehaviourに変わっています.

関数の呼び方

using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour {

    void Start () {
        // クラス名.Instance.関数
        GameManager.Instance.Test ();
    }
}

演習

  1. 新しく,TestManagerという名前のスクリプトを作成しシングルトンにしよう
  2. TestManagerの中にpublicな関数を作成しよう.
  3. 別のスクリプトからTestManagerの関数を呼んでみよう.
68
52
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
68
52