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, Vector3.zero, Quaternion.identity);
       someObject.AddComponent("OtherExample");
   }
}

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:

gameObject.AddComponent("OtherExample");

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

1 Answer

1

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, Vector3.zero, Quaternion.identity) as GameObject;

go.AddComponent<OtherExample>();

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:

Might I add that when you type gameObject you refer to the game object the script is attached to (and for that matter everything that doesn't start with a capital letter, i.e. 'transform' means the Transform component of the Game Object this script is attached to).

–