Search code examples
c#unity-game-enginedependency-injectioninterfacecomponents

Add interface implementation as a component to a gameobject


Using dependency injection, you can have one same interfaces representing diferent classes, as the class implementation can be bound to the dependency container as per defined at the binding stage of the binding phase. My question is, once your respective bindings are done, if the implementations are monobehaviour, if there is a chance to add the interface as a component to a gameobject.

The story of why I would like to do that is pretty long, so it can be assumed that the necesity just came up :).

Find some pseudoCode for a better understanding:

public interface IFoo {
    //...
}

public class FooIplementtation1: MonoBehaviour {
    //....
}

public class FooIplementtation2: MonoBehaviour {
    //....
}

if (someCondition) {
    Container.Bind<IFoo >().To<FooIplementtation1>();
} else {
    Container.Bind<IFoo >().To<FooIplementtation2>()
}

What I intend to do is:

//Error. Interface type cannot be added as component.
someTransform.gameObject.AddComponent<IFoo>();

But I get the error:

The type IFoo cannot be used as type parameter 'T' in the generic or method GameObject.AddComponent<T>().

The method signature is:

public T AddComponent<T>() where T : Component;

Si I tried to make my interface inherit from Monobehaviour and form Component but that did not work.

Any idea if this is possible and if so , how?


Solution

  • GameObject.AddComponent documentation states

    Adds a component class named className to the game object.

    Component type should be class, it can't be struct nor interface. Interfaces are just a contract that states, class has to implement given interface functions and properties. You are hiding why you are using interface for your code but if it is possible create a base class that contains everything that all classes share same. In short use Polymorphism. Inherit the base class from monobehaviour and you can do what you want to achieve.

    Also think like that interfaces have no data at all. They are just empty implementation, what part of it can be a component for an object? They just make coding easier nothing else. Maybe, you want to look at to the C# Design Patterns.