How to Find a GameObject or a Component in a instantiated Prefab ?


I would like to know how to find and access a GameObject or a Component in a instantiated Prefab, to act on it…

I tried :

GameObject standardMonster = Resources.Load ("Prefabs/Ennemies/MonsterFive");

GameObject monsterCreated = Instantiate (standardMonster);

GameObject rightHand = monsterCreated.Find ("Right Hand").GetComponent<GameObject> ();  //(<---- doesn't work)

Image imageOnTheMonster = monsterCreated.Find ("imageOnTheMonster ").GetComponent ()<Image>;  //(<---- doesn't work)

I can’t use Find Tag as i juste want to access on this clone, not another.
Any idea ? Thanks

Find is not an efficient way to get some component even it worked. Especially if you use it too frequently. Most efficient way to do this is attaching a script to your monster prefab. Let’s say you have left and right arms and legs, head, torso, image components on your monster and you need to access and do specific actions with them. Then create a script like this and assign each part to the script from the inspector:

public class Monster : MonoBehaviour {
    public GameObject leftArm;
    public GameObject rightArm;
    public GameObject leftLeg;
    public GameObject rightLeg;
    public GameObject torso;
    public Image image;

When you instantiate your prefab you could directly get the Monster component and reach all your monster parts via this:

Monster monsterCreated = (Instantiate (standardMonster) as GameObject).GetComponent<Monster>()

It doesn’t work cause Find is a static method of the GameObject class, meaning it cannot be called from an instance. Read up on the static modifier here:

What you are looking for is the Transform.Find method so if you change the code to mosterCreated.transform.Find(“Right Hand”) it should work.