Android

[유니티3D엔진] C# 싱글톤 구현 및 인스턴스 활용

by badung007 posted Oct 28, 2013
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

유니티 엔진에서  C# 싱글톤

 

public class MyHttp : MonoBehaviour

{


      private static MyHttp s_Instance = null;
 
      public static MyHttp instance
      {
            get
            {
                   if (s_Instance == null)
                   {
                         s_Instance = FindObjectOfType(typeof(MyHttp)) as MyHttp;
                   }

                   // 여전히 null일 경우 새로운 인스턴스 생성
                   if (s_Instance == null)
                   {
                         GameObject obj = new GameObject("MyHttp");
                         s_Instance = obj.AddComponent(typeof (MyHttp)) as MyHttp;
                   }
                   return s_Instance;
             }
      }
 
      void OnApplicationQuit()
      {
           s_Instance = null;
      }


}

 

 

유니티 엔진에서  인스턴스 중복 방지

 

public class GameMgr : MonoBehaviour
{
 
        public static GameMgr instance;
 
        void Awake()
        {
                  if(instance != null)  //  DontDestroyOnLoad(this.gameObject); 인해 해당 오브젝트가 계속 쌓이는 것을 방지
                  {
                            //Destroy(this); // 해당 스크립트를 삭제
                           Destroy(this.gameObject); // 해당 오브젝트를 삭제
                           return;
                  }

                  instance = this;
                 //DontDestroyOnLoad(this);
                 DontDestroyOnLoad(this.gameObject);
                 Application.targetFrameRate = 60; // 최대 프레임은 60으로 지정
        }


}