Is it possible to restrict an interface to MonoBehaviours only?
I’m asking this because I want to avoid adding to my interface the GetGameObject() method that I would need to implement in every one of my MonoBehaviour classes using this interface.
Is it possible to restrict an interface to MonoBehaviours only?
I’m asking this because I want to avoid adding to my interface the GetGameObject() method that I would need to implement in every one of my MonoBehaviour classes using this interface.
What I do is create an interface called ‘IComponent’ like so:
public interface IComponent
{
Transform transform {get;}
GameObject gameObject {get;}
}
Then all my component interfaces all inherit from that:
public interface IMyThing : IComponent
{
void Foo()
}
public class MyThing1 : MonoBehaviour, IMyThing
{
public void Foo()
{
}
}
Since ‘transform’ and ‘gameObject’ are already members of MonoBehaviour you don’t have to implement it.
Technically C# won’t restrict it to just MonoBehaviour, but that’s fine. Cause even if you created a class that implements those properties correctly… it still shapes the way you expect.
Examples of it in use by me:
IGameObjectSource:
IComponent inherits IGameObjectSource:
And most all my scripts inherit from SPComponent for some ease of use things that implements IComponent. But IComponent exists just in case I don’t want to inherit from SPComponent, or I can’t inherit from SPComponent:
@lordofduct
I don’t understand why writing this means the transform or gameObject variable is automatically linked to Unity’s Component values. Aren’t those variables equal to null? (since you never set transform/gameObject = to anything)
public interface IComponent
{
Transform transform {get;}
GameObject gameObject {get;}
}
EDIT: Ah no I do understand, these values are already implementend in a Component so it just refers to them, my bad
Thanks it’s great ;D