Search Unity

Custom AddComponent(string) script for Unity 5

Discussion in 'Scripting' started by Fajlworks, Mar 5, 2015.

  1. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    When I installed new Unity 5 I had a couple of compatibility problems, most notably the notorious AddComponent(string name) function.

    I agree using AddComponent<T>() is the way to go since I believe using string to look up class via reflection is not only slow but also error prone. But there are certain cases where adding components with given string comes in handy, especially when you have an external editor.

    I made this handy editor class which will scan for all your .cs files in a given path and create a small extension with all of your classes. It will then compare strings and call function with approriate type. Do note the file can grow quite large :)

    To make it work you can put this script into "Assets/Script/Editor" path.


    It's also quite simplistic, you have to manually enter correct path for it to work, sorry for being lazy >_>

    Now you can just write:

    gameObject.AddComponentX("MyAwesomeAbility");
    // Please note I named the extension method AddComponentX since Unity was complaining AddComponent(string) is obsolete, probably referencing the old method that doesn't work. You can rename it to NewComponent, etc. if you want


    There are few drawbacks though:

    • Whenever you add new classes, you have to manually open Window/GenerateClassBindings and click Generate.
    • It doesn't support nested classes nor multiple classes within same file. First class that gets scanned is added.
    • You have to manually enter path, a file explorer dialogue would come in handy, I admit.

    Of course, if anyone wants to play around please be free to upgrade the script if you want.

    Hope it helps someone save 1-2 hours of coding :) Kind regards!
     

    Attached Files: