Search Unity

Script public variable in a script for adding it to a gameobject at runtime

Discussion in 'Scripting' started by grobonom, May 27, 2019.

  1. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    Hey all :)

    I've been struggling with this for some days.....

    I made a script for building characters at runtime.....
    here's the inspector:
    inspector.jpg

    My problem was to add a script to those created chars, so that they behave in a certain way.
    And i wanted to setup this script in inspector, and not hardcoded in my ingame_toon_builder script.
    Now it works for me like a charm and i post the solution in case it would be of interrest for some ppl...

    It appears not possible to have a
    Code (CSharp):
    1. public MonoBehaviour toon_behaviour_script;
    This won't accept any script from drag'n drop....

    You need to have:
    Code (CSharp):
    1. public UnityEngine.Object toon_behaviour_script;

    you then create the GameObject and add the script to it as a component:
    Code (CSharp):
    1.  
    2.       new_go.AddComponent(Type.GetType(toon_behaviour_script.name));
    3.  
    As the name of a script describes its type, this works fine :)

    Happy Unitying !
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,334
  3. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    thx @Baste :)

    your plugin looks nice ! and pretty well usefull ! i wish i found it when searching for this ;)

    Happy unitying !