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

SingletonとSingletonMonoBehaviourまとめ

Posted at

概要

Singetonパターンは多くのプロジェクトで使われると思いますが、自分で色々なプロジェクトを作っているとプロジェクト間で実装に差が出たり、毎回実装しなくちゃいけなかったりします

自分がよく使っているコードをまとめておきます

Singleton

public abstract class Singleton<T> where T : new()
{
    private static T _instance;
    public static T I => _instance ??= new T();
}
  • 使い方
    Singletonクラスを継承することで、SingletonSample.I.Increment();のようにして呼び出すことができます
public class SingletonSample : Singleton<SingletonSample>
{
    public int Value { get; set; }

    public SingletonSample()
    {
        Value = 0;
    }

    public void Increment()
    {
        Value++;
    }
}

SingletonMonoBehaviour

using UnityEngine;

public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    public static T I
    {
        get
        {
            if (_instance != null) return _instance;

            var foundObjects = FindObjectsByType<T>(FindObjectsSortMode.None);
            _instance = foundObjects.Length > 0 ? foundObjects[0] : new GameObject(typeof(T).Name).AddComponent<T>();
            return _instance;
        }
    }

    protected virtual void Awake() => DontDestroyOnLoad(gameObject);
}
  • 使い方
    Singleton同様に継承して使う
public class SingletonMonoBehaviourSample : SingletonMonoBehaviour<SingletonMonoBehaviourSample>
{
    public int Value { get; set; }

    public void Increment()
    {
        Value++;
    }
}

動作確認用スクリプト

とりあえずSingletonを試したい方向け
適当なオブジェクトに以下のコンポーネントを付けて再生してください

using UnityEngine;

public class Tester : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            SingletonSample.I.Increment();
            Debug.Log(SingletonSample.I.Value);
        }

        if (Input.GetKeyDown(KeyCode.B))
        {
            SingletonMonoBehaviourSample.I.Increment();
            Debug.Log(SingletonMonoBehaviourSample.I.Value);
        }
    }
}

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