# 싱글톤
- 싱글톤 적용 방법
- 기존의 C# 스크립트처럼 Monobehaviour를 상속받아 Hierarchy에 존재하는 방법.
- Monobehaviour을 상속받지 않고 Hierarchy에 존재하지 않는 방법.
# Hierarchy에 존재하는 싱글톤
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
private static GameManager m_instance = null;
public static GameManager Instance
{
get
{
if (null == m_instance)
return null;
return m_instance;
}
}
private void Awake()
{
if (null == m_instance)
{
m_instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
}
}
}
GameManager.Instance; 로 접근 가능
# Hierarchy에 존재하지 않는 싱글톤
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager
{
private static GameManager instance;
public static GameManager Instance
{
get
{
if(null == instance)
{
instance = new GameManager();
}
return instance;
}
}
public GameManager()
{
}
}
GameManager.Instance; 로 접근 가능
- 해당 방법은 씬 이동시의 신경을 안 써도 된다는 장점이 존재한다. 그러나 보통은 1번째 방법을 사용함.
+ readonly는 해당 변수가 읽기 전용임을 나타내는 한정자. 이는 변수가 선언된 후에는 값을 변경할 수 없음을 의미. 주로 변수를 초기화한 후에는 값이 변경되지 않아야 하는 경우에 사용.
'Unity > Activities' 카테고리의 다른 글
[유니티] parent 대입 경고 (0) | 2024.04.08 |
---|---|
[유니티] UI/ IPointer (0) | 2024.04.08 |
[유니티] Json 사용/ 파일입출력 (1) | 2024.04.08 |
[유니티] 외부 폰트 사용하기 (0) | 2024.04.08 |
[유니티] TMP_InputField로 닉네임 입력받기 (0) | 2024.04.08 |