- Home /
How to find an object in children
Hello everyone, in my game there is a prefab enemy which has an empty object called 'enmshotPos'. Every enemy has this. When an enemy shoots it finds the enmshotPos. The problem here is that EVERY enemy has this and it thus finds one specific one. Is there anyway to make it find enmshotPos in its children so it picks the one it parents and not a random one?
Here is the code it finds enmshotPos in:
var enemybullet = Instantiate(enemybullet,
GameObject.Find("enmshotPos").transform.position,
GameObject.Find("enmshotPos").transform.rotation);
enemybullet.rigidbody.AddForce(enemybullet.transform.forward * force);
rate_time = Time.time + rate;
To anyone reading this: thanks a lot for taking the time to read this and thanks for answering if you do decide to do so.
Transform parentObject;
Transform childObject = parentObject.FindChild( "childName" );
Answer by robertbu · Jan 01, 2014 at 05:30 PM
You can use Transform.Find() for this. Note if the object is down the hierarchy, you need to include the path. Say you have the hierarchy of game objects:
Parent
Child1
Child2
Granschild1
Child3
Say your script was on the parent. You would find 'Child3':
var tr : Transform = transform.Find("Child3");
And you would find 'Grandchild1';
var tr : Transform = transform.Find("Child2/Grandchild1");
So for your particular situation, assuming 'enmshotPos' is the child of 'enemybullet' and that enemybullet is a GameObject, you can do:
var tr : Transform = enemybullet.transform.Find("enmshotPos");
var enemybullet = Instantiate(enemybullet, tr.position, tr.rotation) as GameObject;