1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | using UnityEngine; namespace YourNamespace { /// <summary> /// Singleton 패턴을 구현한 클래스. /// 멀티스레드 환경에서도 안전하게 동작하도록 설계됨. /// </summary> public class SingletonPattern : MonoBehaviour { #region Private Fields // Singleton 인스턴스를 저장하는 정적 변수 private static SingletonPattern instance; // 인스턴스 생성 동기화를 위한 락 객체 private static readonly object lockObject = new object(); #endregion #region Getter/Setter Methods /// <summary> /// Singleton 인스턴스를 반환 존재하지 않으면 새로 생성. /// 멀티스레드 환경에서도 안전 /// </summary> public static SingletonPattern GetInstance() { if (instance == null) { lock (lockObject) // 여러 스레드가 동시에 접근하지 못하도록 락 처리 { if (instance == null) // 두 번째 검사를 통해 불필요한 인스턴스 생성을 방지 { // 새로운 GameObject를 생성하고 SingletonPattern 컴포넌트를 추가 GameObject singletonObject = new GameObject(typeof(SingletonPattern).Name); instance = singletonObject.AddComponent<SingletonPattern>(); DontDestroyOnLoad(singletonObject); // 씬 전환 시 파괴되지 않도록 설정 } } } return instance; } #endregion #region Unity Lifecycle /// <summary> /// Unity의 Awake 라이프사이클에서 Singleton 초기화. /// 기존 인스턴스가 존재하면 자신을 파괴 /// </summary> private void Awake() { lock (lockObject) // Awake에서도 락 처리로 스레드 안전성 확보 { if (instance != null && instance != this) { Destroy(this.gameObject); // 중복된 인스턴스 파괴 return; } instance = this; DontDestroyOnLoad(this.gameObject); // 이 오브젝트를 유지 } } #endregion } } | cs |
이런식으로 만들어두면 편하더라.
기본적으로 용도별 분리하고, 자주씀.
팩토리 메서드는 일반적인 템플릿에 제네릭써서 코드 재사용성 늘림.
나만의 푸레임워크를 만드는 즐거움 - dc App
ㄹㅇ