見出し画像

Unityのメモ

ちょっとよく忘れるので自分用のメモです

シングルトン

using UnityEngine;
 
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance; 
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));
 
                if (instance == null)
                {
                    Debug.LogError(typeof(T) + "がシーンに存在しません。");
                }
            } 
            return instance;
        }
    } 
}

public class GameManager : SingletonMonoBehaviour<GameManager>
{
    public void Awake()
    {
        if (this != Instance)
        {
            Destroy(gameObject);
            return;
        }
        DontDestroyOnLoad(gameObject);
    }
 
    void Start()
    {
    }
 
    void Update()
    {
    }
}

この記事が気に入ったらサポートをしてみませんか?