How to reference a game object in a nested hierarchy?

I have the following hierarchy, where there is a BulletRaycast script attached to a prefab. That prefab is used inside the Patrol.cs script. How can I reference the parent game object Enemy inside the BulletRaycast script?

Thank you

├── Enemy (GameObject)
         └── Patrol.cs 
                  └── Bullet (Prefab)
                             └── BulletRaycast.js

In other words, I want to have a variable GameObject enemy inside BulletRaycast script, and automatically assign the Enemy gameobject from the hierarchy above.

Thank you

Hello @erenozakbas .

There are so many ways to achieve that.

Most obvious is, inside BulletRaycast script

GameObject EnemyObject = transform.parent.parent.gameObject;

But you can also find it by searching for a specyfic script in its parents. I supose the Enemy will have some script (called for example EnemyMovement) so you could also do this inside Bullet Script:

GameObject EnemyObject = GetComponentInParent<EnemyMovement>().gameObject;

So you assign the gameObject containing the first EnemyMovement script found in hicheracy “going up”.


If you are asking this, it measn you need to learn about references in Unity, I strongly recommend you ti go look for a tutorial about References, because if you are having this problem now, that is so basic, you will have soooo many preblems in the future unless you learn the “referencing mechanics” of Unity.

Good luck!
Bye.