- Home /
accessing an instantiated prefab's components in C#?
Hi,
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!
Thanks
Instantiate returns type "Object", but can be cast how you like. I think you might have misunderstood the component system though - check my answer for further details.
Nah, the GetComponent is fine. Since it wasn't put in a code block, the generic type went missing
Answer by · Feb 01, 2011 at 02:14 PM
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.
Answer by Mike 3 · Feb 01, 2011 at 02:57 PM
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
I spoke too soon. The cast in the first line to a GameObject throws an exception.
Cast it to whatever type rocket is (and make the instantiatedRocket the same type). Probably Transform if it's not GameObject
Your answer
Follow this Question
Related Questions
Access Child of instantiated UI-Prefab using C# in Unity Beta 4.6 1 Answer
access instantiated object variable 0 Answers
Access a instantiated gameobject from a enemy spawner 4 Answers
Checking if object intersects? 1 Answer
How to access Instantiated gameObjects from a Collection inside for loop? 1 Answer