- Home /
set position child of game object by name
Hi there, I want to set position my child of gameobject based name. How should I do? Here my sample code
GameObject Parent;
foreach(Transform child in Parent.transform)
{
if(child.name == "Child1")
Child1.transform.position = new Vector3(10, 10, 10);
}
there is a sample code, I want to transform child of gameobject with name Child1 to x=10, y=10, z=10 thanks for your response :)
Can you explain your problem. I am not sure to understand what you want. Do you want to set every GameObject with name "Child1" in position 10,10,10 ?
I think you can just replace Child1.transform.position = ... by child.transform.position = ... Or is it the child of the child ? :P
if I replace with child.transform.position = ..... the whole of gameobject at position x=10, y=10, z=10 in this case I just want to set position that contains name Child1
So you want to move the child of the game object named "Child1" ?
Answer by Eugenius · Aug 23, 2013 at 09:26 AM
Just tested the below in Unity on a new project with a Cube parent and Cube children. It works exactly as you mention you would like to. It's in Javascript though.
Hope this helps!
#pragma strict
function Start()
{
for(var child : Transform in transform)
{
if(child.name == "Cube0")
{
child.transform.localPosition.x = 15;
}
if(child.name == "Cube1")
{
child.transform.localPosition.x = 10;
}
}
}
Answer by mattssonon · Aug 23, 2013 at 09:29 AM
You should just change your code to this, to properly access the found child:
GameObject Parent;
foreach(Transform child in Parent.transform)
{
if(child.name == "Child1")
child.position = new Vector3(10, 10, 10);
}
Your answer
Follow this Question
Related Questions
Find position of the GameObject this script is attached to. 2 Answers
Set the ragdoll position 0 Answers
I want to move a cube with rotation but I find this problem 1 Answer
Physics.OverlapSphere() not working after using pool of objects 0 Answers
How could I make a gameobject move above my players head during an animation and then delete it? 1 Answer