본문 바로가기

유니티/정리

유니티에서의 싱글톤 사용.

유니티에서 싱글톤 사용 코드 정리

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance = null;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
                DontDestroyOnLoad(instance.gameObject);
            }
            return instance;
        }
    }
}

 

유니티에서의 싱글톤 사용법.

 

<T>에 상속 받아 사용하는 클래스 이름을 적고, 해당 클래스를 Instance로 리턴하도록 처리.

 

T에 들어 올 클래스는 MonoBehaviour를 상속받아야 함.

 

instance가 null이면 새롭게 게임 오브젝트를 만들도록 처리.