본문 바로가기
Unity/Activities

[유니티] 싱글톤

by 김 원 2024. 4. 8.

# 싱글톤

- 싱글톤 적용 방법

   - 기존의 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는 해당 변수가 읽기 전용임을 나타내는 한정자. 이는 변수가 선언된 후에는 값을 변경할 수 없음을 의미. 주로 변수를 초기화한 후에는 값이 변경되지 않아야 하는 경우에 사용.


참고 자료 : https://glikmakesworld.tistory.com/2