Hi,
I’m trying to make an abstract pseudo-singleton class. It uses FindObjectOfType to ensure uniqueness of the instance, while still allowing several objects to have my class as a component.
But if I want to use FindObjectOfType, I need the type of the concrete class. So I guess the only way out is to have a generic abstract class.
Also, if the instance doesn’t exist yet, I have to initialize it, but the implementation of the initialization depends on the concrete class once again.
And here’s where I’m stuck: the following code won’t compile because there’s no guarantee that my type T will have an initialize method.
using UnityEngine;
using System.Collections;
/// <summary>
/// Used to extend a component of type T and make it behave like a singleton
/// </summary>
/// <example>
/// public class MyClass:AbstractSingletonComponent<MyClass>
/// </example>
public abstract class AbstractSingletonComponent<T>: MonoBehaviour {
// Singleton reference
private static T instance;
// Returns the instance
public static T Instance<T>() {
// If instance is not initialized
if (!instance) {
// Is there an ObjectPoolCollection somewhere in the scene
instance = FindObjectOfType<T> ();
// If not, then the designer forgot to put one
if (!instance) {
Debug.LogError ("There needs to be at least one active ObjectPoolCollection on the scene");
}
// This won't work because we can't guarantee that T has an Initialize method
instance.Initialize ();
}
return instance;
}
abstract void Initialize (); //<----- what to do about this?
}
I guess I’m not taking the problem with the right angle but my mastery of C# is not good enough to know better.