CoffeRight
CoffeRight

Reputation: 143

(Unity) How to get generic component class from GameObject?

How to get a generic component from spawned GameObject In Unity?

I.e i have a base generic class:

class Base<T> : MonoBehaviour where T : MonoBehaviour 
{
    public Foo() {}
}

and derived class:

class Example : Base<Example>
{

}

And I wonder to get this class from spawned GameObject where I attached it as a component.

I was tried this but my result was null so I decided to ask for some help :)

// @object - Spawned before and exists.
Base<MonoBehaviour> tmp = @object.GetComponent<Base<MonoBehaviour>>();

Upvotes: 0

Views: 3550

Answers (1)

Try use interface implementation:

class Base<T> : MonoBehaviour, IBase where T : MonoBehaviour 

And get interface from GO:

var tmp = @object.GetComponent<IBase>();

Upvotes: 3

Related Questions