Singleton - jeongpaljack/Design-Pattern-Unity-CSharp GitHub Wiki
Singleton(์ฑ๊ธํค)
- ์ฑ๊ธํค์ ๋ชฉํ๋ ์ ์ผ์ฑ์ ๋ณด์ฅํ๋ ๊ฒ
- ํด๋์ค๊ฐ ์ฑ๊ธํค ํจํด์ ๊ตฌํํ๋ค๋ฉด ์ด๊ธฐํ๋ ํ์๋ ๋ฉ๋ชจ๋ฆฌ์ ์ค์ง ํ๋์ ์ธ์คํฐ์ค๋ง์ด ์กด์ฌํด์ผ ํจ
- ์ ๋ํฐ์์๋ ๊ฒ์๋งค๋์ , UI๋งค๋์ ๋ฑ ๋งค๋์ ์์คํ
์ ์ฌ์ฉ๋จ
- ์ ์ญ์์ ์ ๊ทผ์ด ๊ฐ๋ฅํด์ผ ํจ
์์ ์ฑ๊ธํค ์ฝ๋
using UnityEngine;
namespace Chapter.Singleton // Chapter ํ์ผ ์์ Singleton ํ์ผ์ด๋ผ๋ ์๋ฏธ
{
public class Singleton<T> : // ์ ๋ค๋ฆญ ํด๋์ค, T์ ์๋ฏธ๋ ๋์ค์ ํ์์ ์ง์ ํ๊ฒ ๋ค๋ ๋ป
MonoBehaviour where T : Component // ์ ๋ค๋ฆญ์ ์กฐ๊ฑด, T์ ํ์
์ ๋ฐ๋์ Unity์ Component ํน์ ๊ทธ ํ์ ํ์
์ด์ด์ผ ํจ
{
private static T _instance; // private static T ํ์์ _instance ์ ์ธ - ํ๋ก๊ทธ๋จ์์ ํ๋๋ง ์กด์ฌํ์ง๋ง, ์ธ๋ถ์์ ์ ๊ทผ ๋ถ๊ฐ๋ฅํ ํจ์
public static T Instance // static ํ์์ Instance ์ ์ธ -> ํด๋น ์ฑ๊ธํค์ ํ์
๋ฐํ ํจ์ -> ์ฑ๊ธํค์ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ ๋ ์ฌ์ฉ
{
get
{
if (_instance == null) // Awake์์ ์ ์ฅํ T ํ์
, ์ฆ _instance์ ํ์์ด ์์ ๊ฒฝ์ฐ
{
_instance = FindFirstObjectByType<T>(); // ์ด๋ฏธ T๊ฐ ์กด์ฌํ ๊ฒฝ์ฐ ์ด๊ฒ์ผ๋ก ๋์ฒด
if (_instance == null) // T๊ฐ ์ต์ข
์ ์ผ๋ก ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ
{
GameObject obj = new GameObject(); // ์๋ก์ด ์ค๋ธ์ ํธ ์์ฑ
obj.name = typeof(T).Name; // ์ค๋ธ์ ํธ์ ์ด๋ฆ(name)์ ํด๋์ค์ ์ด๋ฆ(Name)์ผ๋ก ์ด๊ธฐํ
_instance = obj.AddComponent<T>(); // _instance์ ํ์
์ obj์ T ์ด๋ฆ์ ์ปดํฌ๋ํธ๋ก ์ ์
}
}
return _instance; // Instance์ ๊ฐ์ _instance๋ก ์ง์
}
}
public virtual void Awake() // ์ค๋ธ์ ํธ๊ฐ ํ์ฑํ๋ ๋, ์ ์ผ ๋จผ์ ์คํ -> ์ฑ๊ธํค์ด ํ๋๋ง ์๋๋ก ํ๋ ํจ์
{
if (_instance == null) // _instance๊ฐ ์์ ๊ฒฝ์ฐ, ์ฆ ์ฑ๊ธํค ์ธ์คํด์ค๊ฐ ์์ ๊ฒฝ์ฐ
{
_instance = this as T; // ํด๋น ์ธ์คํด์ค๋ฅผ Tํ์
์ผ๋ก ์บ์คํ
ํ์ฌ ์ ์ฅ
DontDestroyOnLoad(gameObject); // ์ฌ ์ ํ ์์๋ ์ฑ๊ธํค ์ธ์คํด์ค๊ฐ ํ๊ดด๋์ง ์๊ฒ ์ ์ง
}
else
{
Destroy(gameObject); // ์ด๋ฏธ ์ธ์คํด์ค๊ฐ ์์ผ๋ฉด ์๋ก์ด ๊ฒ์ ์ค๋ธ์ ํธ๋ฅผ ์ญ์ ์ํด
}
}
}
}