unity3d 继承Monobehaviour的单例模式基类

2024-01-04  本文已影响0人  午字横

基类代码:
解决加载场景后 单例物体重复的问题;

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

public class SingtonMono <T>: MonoBehaviour where T:MonoBehaviour
{
    private static T intsance;
    public static T Instance
    {
        get
        {
            if (intsance == null)
            {
                GameObject obj = new GameObject();
                obj.name = typeof(T).Name;
                intsance = obj.AddComponent<T>();
                DontDestroyOnLoad(obj);
            }

            return intsance;
        }   
    }

}

子类代码:

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

public class test_01 : SingtonMono<test_01>
{
    public void Print()
    {
        Debug.LogError("test_01 print");
    }


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.A)) SceneManager.LoadScene("scene_01");
        if (Input.GetKeyDown(KeyCode.S)) SceneManager.LoadScene("SampleScene");
    }
}

--------------------------------------------------------------------------------2024-01-05

上一篇下一篇

猜你喜欢

热点阅读