- Home /
How to go up or down to assign a child?
I want to find a child apart of a transform and then go one above or below it. I hope that explains it, its kind of difficult to explain but here's the code:
if (Input.GetKeyDown(KeyCode.W))
{
foreach (Transform child in hook)
{
if (child.name == currentSegment.gameObject.name)
{
//what I want is getting the child I found and then going to the one above it
currentSegment = child++;
}
}
}
else if (Input.GetKeyDown(KeyCode.S))
{
foreach (Transform child in hook)
{
if (child.name == currentSegment.gameObject.name)
{
currentSegment = child--;
}
}
}
What is hook
in this context? Have you tried doing something like child.parent
? You can also chain **.parent**s like so child.parent.parent
because it will always point to a transform - if it exists of course
Hook is the transform that is the parent to the children Im trying to access. The currentSegment is a child that has been assign already but what Im trying to do is go from that one to the above and below it on the children of the hook in the hierarchy.
Edit: Im really sorry if this doesn't make sense Im struggling to explain it
To go above, you can use transform.parent
for any transform. To check for the children one level below, I'd do something like this.
Assuming all children have a Transform component attached to them - which they should by default - you could do a foreach cycle and then check if the current transform.parent is the parent you are looking for, like so:
Transform parent = transform;
foreach (Transform child in transform.GetComponentInChildren<Transform>())
{
if (child.parent == parent) {
// It is the parent's child
}
}
If you want to go more deeper then you have to do it recursively, but you should be careful with that
Answer by Narc0t1CYM · Mar 19 at 06:16 PM
To go above, you can use transform.parent
for any transform. To check for the children one level below, I'd do something like this.
Assuming all children have a Transform
component attached to them - which they should by default - you could do a foreach cycle and then check if the current transform.parent
is the parent you are looking for, like so:
Transform parent = transform;
foreach (Transform child in transform.GetComponentInChildren<Transform>())
{
if (child.parent == parent) {
// It is the parent's child
}
}
If you want to go more deeper then you have to do it recursively, but you should be careful with that.
Your answer
