- Home /
How do I get a specific Child Transform, based on Tag?
I got a bird flying around a scene, and I want it to sit on a specific part of the player when it touches it.
So I made a script, attached to the Bird. But it isn't finished yet. It can detect where the Bird should sit, as soon as it touches the player:
using UnityEngine;
public class Bird : MonoBehaviour
{
Transform birdSittingPoint;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
birdSittingPoint = other.gameObject.transform.GetChild(0);
}
}
But I haven't implemented the act of the bird sitting yet. Before I do, I first want to fix a little problem with the approach on how the Bird Sitting Point is detected.
The key to fetching the Transform is this Line:
birdSittingPoint = other.gameObject.transform.GetChild(0);
But it only works properly if the Bird Sitting Point is the Very first Child Object of the Player, since the (0) in the bracket is the Child Index. However, I don't want the Bird Sitting Point to always be the first Child Object. Instead, I always want it to be that one Child Object that is tagged BirdSittingPoint
. How do I automatically set the Transform Child reference to an Object with a specific tag instead of a fixed Child Index?
Answer by DevedGames · Sep 08, 2019 at 04:51 PM
Hey @Sosasees
you can just iterate over all childs of the gameobject with something like this:
foreach(Transform child in other.transform)
{
if(child.CompareTag("BirdSittingPoint"))
//do stuff
}
LG Max
Your answer
Follow this Question
Related Questions
Grab position from instantiated object 1 Answer
Can't Return the Tag of a Child Object 4 Answers
List and store vector3 of game objects with tag 1 Answer
Help With LookAt Target 1 Answer
Convert a GameObject to a transform? 1 Answer