Accessing gameObjects from a script attached to a master prefab which has those gameObjects inside.

Hello,

I am having an issue here.

  1. I have a prefab which has inside of it 3 other gameobjects.
    (these are: a platform (1st gameobject) with a treasure on it (second gameobject ) and some grass ( third gameobject )
  2. Also that master prefab, which holds those three gameobjects has a script attached to it.

Now my question is. How can I access the treasure prefab from the script attached to the master prefab which holds all the three gameobjects. And I want to access it in a way that I will only access the exact treasure gameobject inside this specific master prefab. (I dont want to get an array of all treasures in instances of the prefab on the scene).

Any good thoughts about it will be welcome!

Thanks in advance!

Ok I found a solution myself. Works good :). Maybe you have any other ideas?

var currentPrefab = transform.GetComponentsInChildren();

foreach (var child in currentPrefab) {
if (child.tag == “treasure”)
{

// do something with the found child

}
}

or you can just have a reference and drag/drop it in the inspector, within the prefab, so long as you are referring to something else in the prefab the references will be retained…

1 Like