How to add a component of unknown type in the Editor

I’m creating an editor extension that allows the user to create prefabs. Right now the user can choose a file using: EditorUtility.OpenFilePanel (which returns a path). The problem is that I can’t then get the type of that script (we can assume that it will always be a valid monobehaviour script). Does anyone know a way to get the type of a script file if you know its name or path? Or if there is another solution. Thanks in advance.

IF you assume that a file called MyMonobehaviour.cs contains a MyMonobehaviour class, then you can just use typeof and GetFileNameWithoutExtension.

If you do not want to assume that, you’ll have to use reflection to try to find a valid Monobehaviour derived type in the file. Keep in mind that .cs files can have as many classes in them as you like.