实例教程Unity3D单例模式(一)通经常使使用方法

时间:2023-11-18 17:49:08
实例教程Unity3D单例模式(一)通经常使使用方法

unity3d教程 中的单例模式通经常使使用方法

通经常使使用方法是在相关类增加GetInstance()的静态方法,检查实例是否存在。假设存在,则返回。假设不存在。则返回一个“须要用游戏元素类关联”的调试警告错误。

public class MyClass   

{  

private static MyClass instance;   

public static MyClass GetInstance()  

{  

if (!instance)  

{  

instance = GameObject.FindObjectOfType(typeof(MyClass));   

if (!instance)  

Debug.LogError("There needs to be one active MyClass script on a GameObject in your scene.");   

}  

return instance;   



}