- Home /
Class that extends another class that extends Singleton generic class
Hi guys,
I'm a begginer in unity world, and i'm actually creating a small 2D game here's my problem:
In my project I used Singleton generic class which I found here: http://wiki.unity3d.com/index.php/Singleton
This was perfect until now, I want to create a class which i'll call Parent this class extends Singleton, and each child of Parent must be a singleton, and I want to know how I can do that?
This doesn't work:
public class Parent : Singleton<Parent>{
protected Parent(){}
public virtual void method(){
}
public void methidForAllChildes(){
}
}
public class Child : Parent{
public override void method(){
}
}
When I call:
(Child.Instance).method();
I get Parent.method() instead of Child.method()
Thanks :D
Answer by KTGLeiden · Dec 19, 2017 at 08:15 PM
Hi there,
I know that I'm completely necroing this thread, but I was searching for this myself just now. Thing is that I have spent the past hour figuring this out and found a nice solution.
The problem of the OP in this question is that the Singleton is actually referring to the parent object since it is defined as Singleton. Child will be a Singleton as well. If you do not know why, please read the rules of inheritance.
The way to fix this is to use generic types, like so:
public class Parent : Singleton<T> where T : MonoBehaviour {
protected Parent(){}
public virtual void method(){
}
public void methidForAllChildes(){
}
}
public class Child : Parent<Child> where T : MonoBehaviour {
public override void method(){
}
}
What this does, is just "bouncing" the "Child" type up into the type, which means that when calling child.Instance.method(), you are really calling to the child method.
I found this generic singleton you can create with this extremely useful.
Cheers,
~Koen