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. e.g.
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.