I am trying to understand why I cannot get a component on a gameobject that derives from a base class that has a generic tied to an interface.
I have the following setup for my class:
MyClass : Node<IMyInterface>
with
abstract Node<T> : Monobehaviour where T : IMyInterface
Then in a separate component on the same gameobject as MyClass
i have:
GetComponent<Node<IMyInterface>>()
This always returns null when i have MyClass
attached to the same GameObject. I also cannot drag the component to a public field of type Node<IMyInterface>
either even though it seems to suggest I can because when I drag it over the field it highlights it as if I am able to set it there.
Why does it not allow this ? I don't see anything wrong here as the types match perfectly fine...
CodePudding user response:
I notice the interface, so I suspect you didn't declare MyClass
as such, but in the following form:
class MyImpl : IMyInterface;
class MyClass : Node<MyImpl>;
Now everything makes sense.
Although Node<MyImpl>
is similar to Node<IMyInterface>
, they are actually different types, the assignment Node<IMyInterface> node = new MyClass();
is invalid, so GetComponent<Node<IMyInterface>>()
cannot find a component which type is Node<MyImpl>
.
In the inspector, both Node<MyImpl>
and Node<IMyInterface>
fields are shown as Node`1
, it's the generic type defination (Node<>
) of these classes, when you drag a Node<MyImpl>
component to a Node<IMyInterface>
field, only the defination is compared, that's why you can see the field highlights but cannot be set.
CodePudding user response:
MyClass : Node<IMyInterface>
abstract Node<T> : Monobehaviour where T : IMyInterface
PreciseClass : Monobehaviour , IMyInterface
GetComponent<MyClass >()//work
GetComponent<Node<PreciseClass>()//not work
GetComponent<PreciseClass>()//work
for example like this.