Unity 单例模式

using UnityEngine;  
using System.Collections;  
using UnityEditor;  

public class MyFont : MonoBehaviour   
{
    private static MyFont _myFont = new MyFont();

    public static Instance
    {
        get{ return _myFont; }
    }

    public void CreatFontConfig(Object data, Object font)
    {
        ......
    }
}  

//引用:MyFont.Instance.CreatFontConfig(m_data, m_myFont);

 

### Unity 中实现单例模式的方法 在 Unity 开发中,单例模式是一种常见的设计模式,用于确保某个类只有一个实例并提供全局访问点。以下是几种常见的方式以及它们的优缺点。 --- #### 方法一:基于 `MonoBehaviour` 的简单单例模式 这种方法适用于需要继承自 `MonoBehaviour` 的类,并且可以在场景之间保持状态不变的情况。 ```csharp public class MySingleton : MonoBehaviour { private static MySingleton instance; public static MySingleton Instance { get { if (instance == null) { instance = FindObjectOfType<MySingleton>(); if (instance == null) { instance = new GameObject("MySingleton").AddComponent<MySingleton>(); DontDestroyOnLoad(instance.gameObject); } } return instance; } } private void Awake() { if (instance != null && instance != this) { Destroy(gameObject); } else { instance = this; DontDestroyOnLoad(gameObject); } } } ``` 此方法通过静态属性 `Instance` 提供全局访问接口,并利用 `Awake()` 函数来确保同一时间只存在一个实例[^2]。 --- #### 方法二:泛型单例模式 对于不依赖于 `MonoBehaviour` 的类,可以使用泛型方式实现单例模式。这种方式更加通用,适合纯逻辑类。 ```csharp using System; public class Singleton<T> where T : class, new() { private static readonly Lazy<T> lazyInstance = new Lazy<T>(() => new T()); public static T Instance => lazyInstance.Value; protected Singleton() { } } // 使用示例 public class GameManager : Singleton<GameManager> { public void SomeMethod() { Console.WriteLine("GameManager Method Called"); } } ``` 上述代码定义了一个泛型单例基类 `Singleton<T>`,并通过子类 `GameManager` 来调用其唯一实例[^5]。 --- #### 方法三:带自动销毁机制的单例模式 为了防止重复创建对象,可以通过检测当前场景是否存在该单例实例来进行优化。 ```csharp public class PlayerSingletonMono : MonoBehaviour { private static PlayerSingletonMono _instance; public static PlayerSingletonMono Instance { get { if (_instance == null) { _instance = FindObjectOfType<PlayerSingletonMono>(); if (_instance == null) { _instance = new GameObject("PlayerSingletonMono").AddComponent<PlayerSingletonMono>(); DontDestroyOnLoad(_instance.gameObject); } } return _instance; } } private void OnApplicationQuit() { _instance = null; } private void OnDestroy() { _instance = null; } } ``` 这种实现方式不仅提供了线程安全的初始化过程,还能够在应用退出或对象销毁时清理资源[^4]。 --- #### 注意事项 1. 如果单例需要跨越多个场景,则应始终调用 `DontDestroyOnLoad(this)`。 2. 对于性能敏感的应用程序,建议减少不必要的单例数量,因为过多的单例可能导致内存泄漏或其他问题。 --- ### 总结 以上三种方法分别针对不同需求进行了优化。开发者可以根据实际项目情况选择最适合自己的实现方式。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值