美文网首页
unity3d 继承Monobehaviour的单例模式基类

unity3d 继承Monobehaviour的单例模式基类

作者: 午字横 | 来源:发表于2024-01-04 15:44 被阅读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

    相关文章

      网友评论

          本文标题:unity3d 继承Monobehaviour的单例模式基类

          本文链接:https://www.haomeiwen.com/subject/mtxbndtx.html