싱글톤 패턴이란?
- 객체의 인스턴스 한개만을 사용하는 것
- 고정된 메모리 영역을 사용하기 때문에 메모리에서 이점이 있다.
- 전역으로 사용될 수 있는 인스턴스이기 때문에 다른 오브젝트에서 접근이 쉽다.
싱글톤 기본 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton1 : MonoBehaviour
{
private static Singleton1 instance = null;
public static Singleton1 Instance
{
get
{
// 다른 곳에서 get을 할 때, instance가 null이면 null를 반환하고
// null이 아니면 instance를 반환한다.
if (instance == null)
{
return null;
}
return instance;
}
}
private void Awake()
{
// instance가 null이면
if (instance == null)
{
// 자기 자신(Singleton1)을 instance에 넣음
instance = this;
// 씬이 전환되어도 자신의 게임오브젝트는 남아 있게 한다.
DontDestroyOnLoad(this.gameObject);
}
else
{
// instance가 null이 아니라면 이미 instance에 자기자신이 있다는 것이기 때문에
// 두개가 되어선 안되어 파괴시킨다.
Destroy(this.gameObject);
}
}
public void Test()
{
Debug.Log("싱글톤 테스트 함수");
}
}
싱글톤 제네릭 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 제네릭타입으로 싱글톤 구현
public class Singleton2<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
if (instance == null)
{
GameObject obj = new GameObject(typeof(T).Name, typeof(T));
instance = obj.GetComponent<T>();
}
}
return instance;
}
}
private void Awake()
{
if (transform.parent != null && transform.root != null)
{
DontDestroyOnLoad(this.transform.root.gameObject);
}
else
{
DontDestroyOnLoad(this.gameObject);
}
}
public void Test()
{
Debug.Log("test");
}
}
다른 스크립트에서 제네릭 싱글톤을 상속받아 사용하면됩니다.
public class GameManager : Singleton2<GameManager>
{
}
[Unity] API Call (Post) (0) | 2022.10.08 |
---|---|
[Unity] API Call (GET) (0) | 2022.10.04 |
[Unity] Mongo DB <---> Unity 데이터 연동 (0) | 2022.10.01 |
[Unity] Resources.Load (0) | 2022.09.29 |
[C#] Action, Func (0) | 2022.09.29 |
댓글 영역