How to access a gameobject in a script of instantiated gameobject?

Hi all.
I intend to access a gameobject (is in a scene) in a script of an instantiated gameobject.
I can use GameObject.FindGameObjectWithTag or use parent or getchild findchild
I can not assign the gameobject to it by using inspector because it is a prefab
So do I have another or better way?

Keep a reference to it when you instantiate it. Then use that reference to access it using getcomp etc. the other way is to have the object check in to a manager script once it is created.

2 Likes

Thanks.
so I create a script to instantiate them and send the gameobject as a parameter of a function like initialize

When you instantiate,
You can do something like
GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;

Then ‘instance’ can be added to an array of some type. Then you have a reference to the gameobject.

you didn’t know my question
I think you need to read again
I don’t want to have a reference to my instantiated gameobject
However thanks I solved that

You mean (this.)transform.gameObject? Or maybe I misunderstood you as well.

It’s a good idea to post your solution, if you got one (either on your own or with help from the thread). Future readers can see your solution in case they are in a similar situation. :slight_smile:

1 Like

I said here. In a script called controller, I instantiate my prefab and call its Initialize function with parameters(like the gameobject that I want to access in the instantiated gameobject)

public class CController:Monobehaviour{
   [SerializeField]
   GameObject obj;
   [SerializeField]
   GameObject prefab;
   public void Create(){
      GameObject prefabObj=Instantiate(prefab);
      prefabObj.GetComponent<CScript>().Initialize(obj);
   }
}
1 Like

Yeah, perfect solution.
I’d recommend adding the Instantiated objects to a list, that way you can always reference them again without having to 'find 'them if you need them again. i.e.,

Outside of method:

public Dictionary<string, GameObject>  prefabObjDict = new Dictionary<string, GameObject>();

In your Instantiate code:

prefabObj[i] = prefabObj;

Y

Yes I know it thanks:)