'Unity : Cast a gameObject as custom monobehavior class

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.



Solution 1:[1]

Doesn't GetComponent answer for this?

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KiynL