Search Unity

Possible to add script by name at runtime?

Discussion in 'Scripting' started by sarachan, Jan 16, 2017.

  1. sarachan

    sarachan

    Joined:
    Jul 21, 2013
    Posts:
    43
    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
     
  2. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    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).
     
    Simski likes this.
  3. sarachan

    sarachan

    Joined:
    Jul 21, 2013
    Posts:
    43
    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
     
  4. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
  5. sarachan

    sarachan

    Joined:
    Jul 21, 2013
    Posts:
    43
    Thanks for the information. This is very helpful!
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.
     
  7. sarachan

    sarachan

    Joined:
    Jul 21, 2013
    Posts:
    43
    Super, thanks!