I have a variable which references an interface, and there’s a class behind it. But now I need to create a new() reference and I have no way of currently knowing which class lies underneath it. I can access the name through GetType but then its hard to extract that particular class. When it comes to GameObject its just “Instantiate”, but this item could be any of class, but all these classes share the same interface.
Is there a way to create a new instance of a class from its interface, without explicitly stating the class type?
IMyInterface thisIsTheOriginal = MyMagic();
IMyInterface butIneednewone;
IMyInterface andanothernewone
You could add a method to the interface:
IMyInterface CloneThyself();
Then you can have every class that implements that interface do the instantiation of the proper type:
public class SomeClass : IMyInterface {
public IMyInterface CloneThyself() {
return new SomeClass();
}
}
1 Like
Thanks to your asking this question, today I learned:
using UnityEngine;
public interface IFnordable { }
public class POCO : IFnordable { }
public class CreatingClassesFromInterfaces : MonoBehaviour, IFnordable
{
void Start ()
{
// with regular old classes
{
IFnordable fnord = new POCO();
var type = fnord.GetType();
var poco = (POCO)System.Activator.CreateInstance(type);
Debug.Log( poco.ToString());
}
// with monobehaviors (add ourself)
{
IFnordable fnord = this;
var type = fnord.GetType();
var comp = gameObject.AddComponent(type);
Debug.Log( comp.ToString());
}
// so we don't just keep looping on our fresh self-copies forever!
Debug.Break();
}
}
Stick that on a GameObject in scene and press PLAY. Pretty cool! I had no idea.
1 Like