1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Unity] シングルトン Singleton

Posted at

0.0 はじめに

利用頻度が高いデザインパターンの一つ、シングルトンの実装方法です。
自分用の備忘録として掲載しています。

1.0 特徴

自分なりに理解したシングルトンの特徴です。

  • クラスが自身のインスタンスを1つだけ作成できることを保証する
  • そのインスタンスに、簡単にどこからでもアクセスできる

2.0 シングルトン(Singleton) クラスの作成

できるだけシンプルにしています。

  • 新しいシーンをロードしても、GameObjectは破壊されません
  • このクラスを使用すれば、ヒエラルキーでいちいち設定する必要がありません
  • ジェネリックを使用しているので、複数のクラスでシングルトンを使用できる
C# Singleton.cs
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {

    // インスタンス設定
    private static T i;
    public static T I {
        get {
            if (i == null) {
                i = (T)FindObjectOfType(typeof(T));

                if (i == null) {
                    Debug.LogError(typeof(T) + " is nothing");
                }
            }

            return i;
        }
    }

    // DontDestroyOnLoadで永続化、その他の場合は破棄する
    protected virtual void Awake() {
        if (this != I) {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
    }

}

3.0 参照方法

下記ように宣言してクラスをシングルトンにします。
必要なときはGManager.Iで参照することができます。

C# GManager.cs
// Singletonクラスを継承、<>にクラス名を入れる
public class GManager: Singleton<GManager>
{
    // 本体
}

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?