为基类的每个子项创建一个静态变量并获取它

时间:2013-11-22 09:48:10

标签: c# inheritance unity3d

我有一个抽象的管理器类'ManagerBase',我想要派生它并且有多个子节点都有静态引用。

public abstract class ManagerBase<T> : MonoBehaviour {

public static T SharedInstance = default(T);
static bool _sharedInstanceSet = false;

/// <summary>
/// Awake this instance, assigning the shared instance. Important this awake function gets called for each derived class
/// </summary>
protected virtual void Awake() {

    if (_sharedInstanceSet != false) {

        if (BaseManagerVars.ShouldOverwritePrevious == true) {
            Toolbox.GetTools.DestroyObject(SharedInstance.gameObject); //ERROR T does not contain definition of 'gameObject' (FYI is a variable in MonoBehaviour)
        }

        else {

            Toolbox.GetTools.DestroyObject(this.gameObject);
            Debug.Log("Duplicate manager " + this.gameObject.name + " will be deleted");
            return;
        }
    }
    SharedInstance = this;   //ERROR Cannot convert type ManagerBase<T> to T
    _sharedInstanceSet = true;
}

喜欢这样

public class EventMessageManager : ManagerBase<EventMessageManager>  {

}

理想情况下,我希望能够使用继承的变量'SharedInstance'

来访问'EventMessageManager'的共享实例

喜欢

EventMessageManager.SharedInstance.whatever();

我如何才能获得此功能?您可以看到我已将编译错误注释到基本管理器类。

我最初在'MangerBase'中使用静态变量,就像这样

public static ManagerBase<T> SharedInstance

但要获得儿童的静态参考文章太长而且不够整洁

EventMessageManager manager = EventMessageManager.SharedInstance as EventMessageManager;

提前致谢

2 个答案:

答案 0 :(得分:2)

我不确定你为什么要做这样的模式(一些额外的信息可能有帮助),但以下应该有效:

public abstract class ManagerBase<T> : MonoBehaviour where T : ManagerBase<T>

SharedInstance = this as T;

答案 1 :(得分:0)

您可以创建一个方法getSharedInstance(),它从字典中返回该类型的共享实例,问题是它需要构造函数或静态init方法。像这样:

private static Dictionary<Type, object> SharedInstances;

public static init()
{
     if (!SharedInstances.ContainsKey(T.getType()))
     {
           SharedInstances.Add(T.getType(), default(T));
     }
}

public static T getSharedInstance()
{
     return (T)SharedInstances[T.getType()];
}