Reputation: 125
I have an abstract manager class 'ManagerBase' which I want to derive and have multiple children from it that all have static references.
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;
}
Like so
public class EventMessageManager : ManagerBase<EventMessageManager> {
}
Ideally I would like to be able to access the shared instance of 'EventMessageManager' by using the inherited variable 'SharedInstance'
like
EventMessageManager.SharedInstance.whatever();
How might I go about getting this functionality? You can see I have commented in the compile errors to the base manager class.
I was originally using a static variable in the 'MangerBase' like so
public static ManagerBase<T> SharedInstance
But to get the static references of children was too long and not as neat looking
EventMessageManager manager = EventMessageManager.SharedInstance as EventMessageManager;
Thanks in advance
Upvotes: 3
Views: 1028
Reputation: 8367
You can create a method getSharedInstance() which returns the shared instance of the type from a dictionary, the problem is that it need a constructor or static init method. like this:
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()];
}
Upvotes: 0
Reputation: 5402
I'm not sure exactly why you want to do such a pattern (some additional info might help), but the following should work:
public abstract class ManagerBase<T> : MonoBehaviour where T : ManagerBase<T>
and
SharedInstance = this as T;
Upvotes: 2