- Home /
Finding children of an instantiated object
I'm spawning a vehicle, and wish to link the left and right tyres that get spawned as part of the prefab's array.
playerCarBody = Instantiate (carPrefabs[0], playerCarSpawn.position, playerCarSpawn.rotation); playerCarAudio = playerCarBody.audio;
// Here's the tricky bit frontPlayerTyres[0] = gameObject.Find("Wheel_Left").transform; frontPlayerTyres[1] = gameObject.Find("Wheel_Right").transform;
Specifically, I want to be able to search only in the child of that instantiated car, so in essence I want to do a Find(playerCarBody.Find("Wheel_Left") sort of thing.. I'm not quite sure of the syntax on how to do that one :)
Answer by · Sep 23, 2010 at 05:25 AM
I think you're looking for Transform.Find
function Find (name : string) : Transform
Finds a child by name and returns it.
Updated
Note that you can do the same with GameObject.Find, if you pass in a specific search path.
// This will return the game object named Hand, which is a child of Arm -> Monster.
// Monster may not have a parent in the hierarchy view!
hand = GameObject.Find("/Monster/Arm/Hand");
So for your example, you'd want:
frontPlayerTyres[0] = gameObject.Find("/playerCar/Wheel_Left").transform;
// where 'playerCar' is the name of the object instantiated from the playerCarBody prefab.
Nearly, but it sent me on the right path.. Because there are several vehicles with identical names, that didn't quite work.
What did work was frontPlayerTyres[0] = playerCarBody.transform.Find("Wheel_Left") :)
Ah, good to hear it. I upvoted the question as I'm sure it's something that others will want to know.