Unity单例模式的使用

**

Unity单例模式

**
单例模式:在设计一个类时,需要保证整个程序在运行期间只存在一个实例对象。

using UnityEngine;
Public abstract class SingLeton<T>:MonoBehaviour where T :MonoBehaviour
{
    
    
     private static T _instance;
     public static T Instance
     {
    
    
           get
            {
    
    
                returen _instance;
            }
     }

     protected virtual void Awake()
     {
    
    
           _instance = this as T;
     }
     
     //或者
     //protected abstract void Awake();
}

在其他脚本的class中引用

//实现抽象类
Public class EnemyEavm:SingLeto<EnemyEavm>

//或者
protected override void Awake()
{
    
    
   throw new system.NotImpCementedException();
}

其他脚本就可以使用这个函数调用这个脚本中的方法

脚本名.Instance.方法

猜你喜欢

转载自blog.csdn.net/qq_45598937/article/details/126145244
今日推荐