Search Unity

Attach script at runtime

Discussion in 'Scripting' started by littlelingo, Aug 16, 2006.

  1. littlelingo

    littlelingo

    Joined:
    Jul 18, 2006
    Posts:
    372
    I read a bunch of posts on this but am still sort of confused. Can I attach a script to a GameObject at runtime? If so, how would I do this?

    Thanks!

    -- Clint
     
    Deleted User likes this.
  2. Der Dude

    Der Dude

    Joined:
    Aug 7, 2006
    Posts:
    213
    Sure you can.

    // Adds the script named FoobarScript to the game object
    gameObject.AddComponent ("FoobarScript");

    // Adds the sphere collider to the game object
    gameObject.AddComponent ("SphereCollider");

    Might I also direct your attention here:

    http://unity3d.com/Documentation/ScriptReference/20_class_hierarchy.html

    This tells you what Objects you can create and how to access them. It also has a lot of Code Examples. The code above is actually copied from there, due to my laziness.

    So remember, the docs are your friend.
     
    Deleted User and mmourlam like this.
  3. littlelingo

    littlelingo

    Joined:
    Jul 18, 2006
    Posts:
    372
    Thanks for the help and the link!

    -- Clint
     
  4. LukeKozakPL

    LukeKozakPL

    Joined:
    Dec 22, 2014
    Posts:
    3
    Link is dead.
     
  5. Dave-Carlile

    Dave-Carlile

    Joined:
    Sep 16, 2012
    Posts:
    967
    Necro from 2006, that's impressive. I didn't even know Unity was around then, and it was apparently version 2 based on that link.
     
    TaleOf4Gamers likes this.