David Rios
David Rios

Reputation: 161

How to find a sibling GameObject by name; Unity2d c#

I am trying to develop a small 2D Unity platformer to learn to work with Unity's interface. I have been having an issue trying to make a gameobject track clones of an enemy and follow it. The function is to make it so when you hover on the enemy clone, it shows the enemy's health. But when I hover on the enemy, it tracks the position of the original enemy, not the clone. Both gameobjects have the same name. What I want is the GameObject HoverDataDisplay (as shown in the screenshot) to track its sibling, Enemy.

Hierarchy view of Enemy and clone.

The current code that I have for the tracking script is as shown:

        private GameObject Enemy;

void Start() {

    Enemy = GameObject.Find ("Enemy");
}

void Update(){
    transform.position = new Vector3 (Enemy.transform.position.x - 0.57f, Enemy.transform.position.y + 1.5f, Enemy.transform.position.z);

}

But the GameObject (HoverDataDisplay) Only follows the original enemy.

Thanks for your help!

Upvotes: 2

Views: 8414

Answers (2)

Joe Giusti
Joe Giusti

Reputation: 179

You can get a reference to the parent then search through the parents children

    // get a reference to the rb of the parent
    parentRigidbody = gameObject.GetComponentInParent<Rigidbody>();

    // a reference to the camera in a sibling object
    playerCam = rigRigidbody.gameObject.GetComponentInChildren<Camera>();

Upvotes: 1

Programmer
Programmer

Reputation: 125455

In Unity, you can use the forward slash "/" to find a Child of an Object. Since the name of the parents are different, you can easily find them like this:

GameObject.Find("EnemyObject/Enemy");

And the second HoverDataDisplay:

GameObject.Find("EnemyObject(Clone)/Enemy");

It's not really a good idea to let your GameObject use the default "Clone" name. You should rename it after instantiating it so that it will be easy to find. Only do this if you need to find the Object after instantiating it.


This script is attached to the HoverDataDisplay GameObject

You can actually get it's parent Object which is either EnemyObject or EnemyObject(Clone) with transform.parent then use the FindChild to find the enemy Object.

//First, Find the Parent Object which is either EnemyObject or EnemyObject(Clone)
Transform parent = transform.parent;

//Now, Find it's Enemy Object
GameObject enemy = parent.FindChild("Enemy").gameObject;

I recommend you use this method instead of the first one I mentioned. The first one is mentioned so that you will know it can be done.

EDIT:

Transform.FindChild is now deprecated. You can use Transform.Find to do that same exact thing.

Upvotes: 4

Related Questions