728x90
반응형
싱글톤 패턴의 특징
1. 딱 하나의 인스턴스만 생성한다.
2. 다른 객체들이 어디서든 접근할 수 있다.
구현 방식에는 두가지가 있다.
MonoBehaivour를 상속해서 Hierarchy의 오브젝트에 추가해 존재하거나,
상속하지 않고 만들어서 코드상에만 존재하는 방식이 있다.
싱글톤
using UnityEngine;
public class SingletonExample : MonoBehaviour
{
private static SingletonExample instance;
public static SingletonExample Instance
{
get
{
if(instance == null)
{
instance = FindObjectOfType<SingletonExample>();
if(instance == null)
{
GameObject singletonObject = new GameObject(typeof(SingletonExample).Name);
instance = singletonObject.AddComponent<SingletonExample>();
}
}
return instance;
}
}
void Awake()
{
// 씬 넘어가도 안 사라지게
DontDestroyOnLoad(gameObject);
}
}
제네릭 싱글톤
MonoBehaviour 상속 O
using UnityEngine;
public class SingletonBase <T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = FindObjectOfType<T>();
if(instance == null)
{
var obj = new GameObject(typeof(T).Name);
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
}
MonoBehaivour 상속 X
public class BaseSingleton<T> where T : class, new()
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
instance = new T();
return instance;
}
}
}
제네릭 싱글톤 사용방법
public class TestClass : SingletonBase<TestClass>
{
// ...
}
여러가지 간단한 방법
using UnityEngine;
public class SingletonBase<T> : MonoBehaviour where T : MonoBehaviour
{
private static SingletonBase<T> instance;
public static SingletonBase<T> Instance
{
get{
if(instance == null)
instance = GameObject.FindObjectOfType<SingletonBase<T>>();
return instance;
}
}
}
using UnityEngine;
public class SingletonBase<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
void Awake()
{
Instance = this as T;
}
}
728x90
반응형
'Unity' 카테고리의 다른 글
Unity Input System과 Input Action 사용법 (0) | 2024.06.03 |
---|---|
Unity foreach에서 index 사용하는 방법 (0) | 2024.05.03 |
Unity toString() 숫자 표기하기 소수점, 두자리수, 콤마 (0) | 2024.04.18 |
Unity 진동이 있는 디바이스 체크 (0) | 2023.01.19 |
Unity iOS review popup (0) | 2023.01.19 |