Possible to add script by name at runtime?

I am creating an editor tool that will automatically assemble an object with needed components and scripts. The available scripts could be extended in the future as new C# classes that are derived from existing base classes.

What I would like to do is something like:
myObject.AddComponent(“myScriptName”);

However, the method above is obsolete and no longer supported.

It is possible to do this:
myObject.AddComponent(myScriptType);

I have this working now by having built a small lookup table from script names (string’s) to script types (Type’s). Ideally, that would not be necessary, because the lookup table itself needs to be updated when there is a new script. (I do have Editor code working that finds the relevant scripts by name.)

Is there a way currently in Unity to add a script component by name? I have tried a few things that I thought might work, but have not been able to figure this out.

Any information will be much appreciated.
Brion

What is the difference between the name of a script and its type? If you need to convert a string of a type to an actual type reference, you can use Type.GetType(string).

1 Like

Wow, that worked!

Where is Type.GetType(string) documented? It is not in the Unity Scripting API Reference. Also, I could not find it in the .NET / C# docs, although I may have missed it there.

For anyone else interested, I did find that it is necessary to have “using System;” for this to work.

Thanks!
Brion

The Type class is documented on msdn (Type.GetType Method (System) | Microsoft Learn). Unity has access to many of the classes that are standard to .NET. Some examples that are commonly used are System.IO, System.Collections.Generic and System.Linq. These won’t be documented by Unity. I suggest browsing the msdn documentation, such as the framework class reference (.NET Framework Class Library Reference | Microsoft Learn) and experimenting.

Thanks for the information. This is very helpful!

If you are jumping into editor scripting, you really want to dive into reflection. Reflection allows you to browse the types you have, and then do cool things with them.

It’s an absolute must for generic editor scripting.

Super, thanks!