简体   繁体   中英

Is there a way to populate a base class singleton instance with a derived class?

I have a base player class, which contains a Singleton declaration. I want to populate the baseClass.Instance var with derivedClass, if at all possible.

My current approach is that, when the derivedClass "wakes up," it attempts to set Instance = this; I have also tried calling base.Init(), then setting Instance = this; within the base.Init() method. This sets Instance != null, but Instance != derivedClass either.

// Current approach
public 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 approach
public class FPSPlayer : BasePlayer
{
    void OnEnable()
    {
        base.Init();
    }
}
// Also tried
public class FPSPlayer : BasePlayer
{
    void OnEnable()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != null)
        {
            Active = false;
            Destroy(this.gameObject);
        }

        if (Instance == this)
        {
            ...
        }
    }
}

Use a factory class to return your singleton instance. eg

public static class PlayerFactory
{
   private static BasePlayer _instance;

   public static BasePlayer Instance 
   {
      get { return _instance; }
      protected set { _instance = value; }
   } 
}

which should accept any object descended from BasePlayer as the single instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM