如何为继承的 类 即兴创作单例?

How to improvise singleton for inherited classes?

class A
 {
     public static A Instance {get; private set;}

     protected virtual void Awake()
     {
         Instance = this;
     }
 }

 class B : A
 {
     protected override void Awake()
     {
         base.Awake();
     }

     public void Bmethod()
     {
         //do smth
     }
 }

 class C
 {
     private void SomeMethod()
     {
         B.Instance.Bmethod();
     }
 }

所以,这就是例子。我知道这是不可能的。 我的问题是我怎样才能以类似的方式实现这个,不要太长?

我想出了一个主意,但仍然认为必须有另一个更好的主意。

class C
 {
     private void SomeMethod()
     {
         B.Instance.gameObject.GetComponent<B>().Bmethod();
     }
 }

我总是有一个通用的 class 来创建我的单例。我先创建一个摘要 class,像这样:

using UnityEngine;

public abstract class MySingleton<T> : ClassYouWantToInheritFrom where T : MySingleton<T>
{
    static T _instance;
    public static T Instance
    {
        get
        {
            if(_instance == null) _instance = (T) FindObjectOfType(typeof(T));
            if(_instance == null) Debug.LogError("An instance of " + typeof(T) +  " is needed in the scene, but there is none.");
            return _instance;
        }
    }

    protected void Awake()
    {
        if     ( _instance == null) _instance = this as T;
        else if(_instance != this ) Destroy(this);
    }
}

现在,您将此脚本放在项目的某个位置,再也不会碰它。

要创建继承 ClassYouWantToInheritFrom 的单例,您需要 class 继承自 MySingleton< MyClass > 而不仅仅是 ClassYouWantToInheritFrom,因为 MySingleton 已经继承了它。 因此:

public class MyClass : MySingleton<MyClass>
{
}

而不是

public class MyClass : ClassYouWantToInheritFrom
{
}

希望这对您有所帮助:)