[Unity] Singleton 패턴

Yerin·2023년 6월 12일
0

@Managers 오브젝트가 여러개 복사되더라도 유일성이 보장되도록 코드 수정

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

public class Managers : MonoBehaviour
{

    static Managers Instance; // 유일성이 보장된다.
    public static Managers GetInstance() { return Instance; } // 유일한 매니저를 갖고온다.
   
    
    // Start is called before the first frame update
    void Start()
    {
        GameObject go = GameObject.Find("@Managers");
        Instance = go.GetComponent<Managers>();
         
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Player 스크립트에서 Managers 스크립트를 호출하는 형태도 간단하게 바뀜

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

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Managers mg = Managers.GetInstance();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

❗ 만약 아래 코드에서 @Managers를 발견하지 못한다면? -> ❗ 오류 발생

GameObject go = GameObject.Find("@Managers");
Instance = go.GetComponent();

@Managers가 없을 경우에 예외처리를 함

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

public class Managers : MonoBehaviour
{

  static Managers Instance; // 유일성이 보장된다.
  public static Managers GetInstance() { Init(); return Instance; } // 유일한 매니저를 갖고온다.
 
  
  // Start is called before the first frame update
  void Start()
  {
      Init();    
  }

  // Update is called once per frame
  void Update()
  {
      
  }

  static void Init() 
  {
      if (Instance == null)
      {
          GameObject go = GameObject.Find("@Managers");
          if (go == null)
          {
              //빈오브젝트를 생성한다.
              go = new GameObject {name = "@Managers"};
              go.AddComponent<Managers>();
          }

          // 마음대로 추가하고 삭제할 수 없도록 함.
          DontDestroyOnLoad(go);
          Instance = go.GetComponent<Managers>();
      }
  }
}

@Managers는 어지간해서는 삭제되지 않게됨

GetInstance()를 프로퍼티 형식으로 변환

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

public class Managers : MonoBehaviour
{

  static Managers s_instance; // 유일성이 보장된다.
  public static Managers Instance { get { Init();  return s_instance; } } // 유일한 매니저를 갖고온다.
 
  
  // Start is called before the first frame update
  void Start()
  {
      Init();    
  }

  // Update is called once per frame
  void Update()
  {
      
  }

  static void Init() 
  {
      if (s_instance == null)
      {
          GameObject go = GameObject.Find("@Managers");
          if (go == null)
          {
              //빈오브젝트를 생성한다.
              go = new GameObject {name = "@Managers"};
              go.AddComponent<Managers>();
          }

          // 마음대로 추가하고 삭제할 수 없도록 함.
          DontDestroyOnLoad(go);
          s_instance = go.GetComponent<Managers>();
      }
  }
}

profile
재밌는 코딩 공부

0개의 댓글