using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if (instance == null)
{
GameObject obj = new GameObject(typeof(T).Name, typeof(T));
instance = obj.GetComponent<T>();
}
}
return instance;
}
}
void Awake()
{
if (transform.parent != null && transform.root != null)
{
DontDestroyOnLoad(this.transform.root.gameObject);
}
else
{
DontDestroyOnLoad(this.gameObject);
}
}
}
* 사용하기
public class GameManager : Singleton<GameManager>{
}
'Client > Unity' 카테고리의 다른 글
Unity Protobuf 설치 (2) | 2024.09.01 |
---|---|
Unity) 항상 카메라를 바라보는 UI (0) | 2024.06.24 |
Unity) Frame Rate 설정 (0) | 2024.05.12 |
Unity) CharacterController에서 transform.position이 작동하지 않을 때 (0) | 2024.05.10 |
Unity) Input system - 이동 (0) | 2024.05.04 |