Degulleo3D/Assets/KSH/Singleton.cs
2025-04-16 17:19:58 +09:00

46 lines
1.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public abstract class Singleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
_instance = obj.AddComponent<T>();
}
}
return _instance;
}
}
void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject); // obj가 destory 안되도록 설정
// 씬 전환시 호출되는 액션 메서드 할당
SceneManager.sceneLoaded += OnSceneLoaded;
}
else
{
Destroy(gameObject);
}
}
protected abstract void OnSceneLoaded(Scene scene, LoadSceneMode mode);
}