Home > OS >  Unity : Cast a gameObject as custom monobehavior class
Unity : Cast a gameObject as custom monobehavior class

Time:05-13

Is there a way to cast a gameObject as an instance of a monobehavior class? The gameobject has a script component linked with that very class.

I have an instance of a custom class, called 'HeroUnit', inheriting from monobehavior. I got it by Instantiating a prefab. I'd like to link this instance to a field of a scriptableobject that expects a 'HeroUnit', but I get an error saying it's a gameObject instead.

So... do I somehow cast my GameObject as a 'HeroUnit'? I can see the gameobject has a 'Script' component associated with my 'HeroUnit' class.

CodePudding user response:

Doesn't GetComponent answer for this?

var _heroUnit = gameObject.GetComponent<HeroUnit>();
  • Related