Attach script at runtime

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

1 Like

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.

2 Likes

Thanks for the help and the link!

– Clint

Link is dead.

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.

1 Like