accessing an instantiated prefab's components in C#?


How do I go about getting access to a newly instantiated prefab's components?

In C# Instantiate does not return a GameObject so this does not work:

GameObject rocket = Instantiate(rocket, position, rotation);

Component comp = rocket.GetComponent(); //nope!


GetComponent "returns the component of Type type if the game object has one attached, null if it doesn't."

function GetComponent (type : Type) : Component

You need to specify which component you wish to access. If it's one of the standard components, you can access it directly - check the list on the Component script reference page.

For example, `rocket.rigidbody` directly references the rigidbody component of the rocket.

You need to cast the return of the Instantiate.

GameObject instantiatedRocket = (GameObject)Instatiate(rocket, position, rotation);
Component comp = instantiatedRocket.GetComponent<Component>(); //this should work now