Instantiate a prefab and add a script to it

I would like to instantiate a prefab and then add a c# script to it, but I am having some troubles. This is my code so far:

public class Example : MonoBehaviour
   public GameObject someObject;

   void Start ()
       Instantiate(someObject,, Quaternion.identity);

As far as I can tell this should work, but when I run the game the someObject that is instantiated doesn’t have the OtherExample.cs script attached to it. However, if I go:


it WILL add the OtherExample.cs script to the base game object. Any help with this would be much appreciated. Thanks!

You are still trying to add the component to someObject, which is still a just a reference to the original GameObject.

Do this rather…

var go = Instantiate(someObject,, Quaternion.identity) as GameObject;


Also if you are using C#, use the generic versions of AddComponent/RemoveComponent where possible, those are the ones with the <> brackets. It makes for easier picking up of issues/typos at compile time :slight_smile: