Search Unity

Add script during runtime

Discussion in 'Scripting' started by pqmt4fyt, Jun 26, 2019.

  1. pqmt4fyt

    pqmt4fyt

    Joined:
    Jun 17, 2019
    Posts:
    9
    There is a API reference that contains AddComponent, but it seems to have been made obselete (and it throws compiler error). No updated link has been found in the manual.

    Any other link found points to these forums, and are at most recent from 2016. Is there a new way to do it?
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    I think only the string version is obsolete.
    Don't use
    gameObject.AddComponent("MyScript");

    Use
    gameObject.AddComponent<MyScript>(); // returns the created script
     
    pqmt4fyt likes this.
  3. pqmt4fyt

    pqmt4fyt

    Joined:
    Jun 17, 2019
    Posts:
    9
    I literally have
    Weird, had to explicitly specify gameObject in order to access it.
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Oh yeah, AddComponent adds to the object you call it on, so gameObject will get the new component added to it. You couldn't then add it to some other object, so if you are making a new object you want to place a script on, it would look like this
    Code (csharp):
    1. GameObject someObName = new GameObject("I have a name!");
    2. MyScript ms = someObName.AddComponent<MyScript>();
    3. ms.someInt = 256;
    4. // ... etc
     
    Joe-Censored likes this.