본문 바로가기

Design Pattern/유니티에 적용해보기

C#(Unity) - 싱글톤

1. 특징

ㆍ스크립트의 인스턴스가 단 하나만 생성되어 있을 때, 어디에서든 이 인스턴스를 통해 접근하기 위한 메소드.

ㆍ생성될 때 단 한번의 생성으로, 해당 스크립트에 접근할 때 마다 생성하는 낭비를 막아줄 수 있습니다.

ㆍ어디에서든지 접근이 가능하기 때문에 남용하게 된다면 결합도와 의존도가 증가해 객체지향 프로그래밍이 추구하는 방향과는 먼 결과를 낳게 됩니다.

ㆍEager, Lazy, Locking, Holder 등 다양한 방식이 있지만 우선은 기본적이고 쉬운 형태인 Eager Singleton 방식만을 서술하겠습니다.


2. 스크립트

※ 싱글톤 클래스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton<T> : MonoBehaviour
    where T : class
{
    private static T instance;
    public static T Instance => instance;

    private void Awake()
    {
        instance = GetComponent<T>();
    }
}

 

※  싱글톤을 상속하는 클래스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : Singleton<GameManager>
{
	public void GameOver()
    {
    	// 게임 종료
    }
}

 

※ 인스턴스로 접근 및 사용

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
	int hp;
    
	void Update()
    {
    	if(hp <= 0)
        {
        	GameManager.Instance.GameOver();
        }
    }
}