Add script component to game object from C#

I’ve been trying to figure out how to attach a MonoBehaviour to a game object from C#. It’s a bit more difficult now that the string version of AddComponent is obsolete. Can still add components that are only known at run-time using reflection. However, loading a script using AssetDatabase returns a Monoscript, not a MonoBehaviour, and since Monoscript doesn’t inherit from Component it cannot be added to the game object using AddComponent<>.

So the last piece of the puzzle is, how can I, using C#, load / whatever a MonoBehaviour (not known at compile time) so that it can be added as a component to a game object? Do I have to use even more reflection to do be able to “extract” the MonoBehaviour from the Monoscript? Or is there an even simpler solution that I’ve missed?

How about gameObject.AddComponent(monoScript.GetClass()); ?

3 Likes

Thanks eisenpony. Can’t believe I missed that. Guess that’s what I get for staying up too late, thinking I had tried all solutions.

Type.GetType(string), Object.TypeOf and typeof are also useful methods to use.

I’m picking MonoBehaviour.GetClass is simply a wrapper for Object.GetType.