我有一个播放器基类,其中包含一个 Singleton 声明。如果可能的话,我想用 derivedClass 填充 baseClass.Instance var。我目前的做法是,当派生类“醒来”时,它会尝试设置 Instance = this; 我也试过调用 base.Init(),然后设置 Instance = this; 在 base.Init() 方法中。这会设置 Instance != null,但 Instance != derivedClass 也一样。// Current approachpublic abstract class BasePlayer : Entity, IPlayerBase{ // Singleton instance, to be populated by the derived class private static BasePlayer _i = null; private static object _lock = new object(); private static bool _disposing = false; // Check if we're in the process of disposing this singleton public static BasePlayer Instance { get { if (_disposing) return null; else return _i; } protected set { lock (_lock) { if(_i == null && !_disposing) _i = value; } } } protected void Init() { if (Instance == null) { Instance = this; } else if (Instance != null) { Active = false; Destroy(this.gameObject); } if (Instance == this) { Debug.Log("Successfully set BaseClass"); ... } }}// Current approachpublic class FPSPlayer : BasePlayer{ void OnEnable() { base.Init(); }}// Also triedpublic class FPSPlayer : BasePlayer{ void OnEnable() { if (Instance == null) { Instance = this; } else if (Instance != null) { Active = false; Destroy(this.gameObject); } if (Instance == this) { ... } }}
1 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
使用工厂类返回您的单例实例。例如
public static class PlayerFactory
{
private static BasePlayer _instance;
public static BasePlayer Instance
{
get { return _instance; }
protected set { _instance = value; }
}
}
它应该接受从 BasePlayer 派生的任何对象作为单个实例。
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消