...
 
Commits (2)
    https://gitcode.net/qq_33205561/unitylitgamefreamwork/-/commit/13bba21d6ecaca5b82ffeb4bad57cb0d13dfb11c 新增创建挂载预制体方法 2023-09-04T14:38:31+08:00 yqian1000 qq_33205561@gitcode.net https://gitcode.net/qq_33205561/unitylitgamefreamwork/-/commit/a89f05f4c623bdcb2e0c6922d26b71f97245d365 创建时候挂载预制体 2023-09-04T14:39:31+08:00 yqian1000 qq_33205561@gitcode.net
using Unity.VisualScripting;
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
_instance = singleton.AddComponent<T>();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
protected virtual void OnEnable()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
}
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
_instance = singleton.AddComponent<T>();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
protected virtual void OnEnable()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
}
static public T CreateSingletonMono(string prefabName, Transform parent = null)
{
if (string.IsNullOrEmpty(prefabName))
{
GameObject prefab = ResourceManager.LoadGamePrefab(prefabName);
GameObject go = GameObject.Instantiate(prefab, parent);
_instance = go.GetComponent<T>();
if (_instance == null)
_instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
return _instance;
}
else
{
return Instance;
}
}
}
\ No newline at end of file