0
\$\begingroup\$

I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.

\$\endgroup\$
0
\$\begingroup\$

On top of the answer of Philipp and Uri Popov, You need code something like given below(comments for demonstration):

    //make a public  static list for saving all the objects ref you are instantiating during runtime
class InstanceManager : MonoBehaviour {
    public static List<GameObject> runtimeGameObjectList = List<GameObject>();
}

//where you are currently instantiating 
GameObject g = Instantiate(myPrefab);
// add this line so that instantiated ref save in the list for later use
InstanceManager.runtimeGameObjectList.add(g);

Now you can do whatever you want with this list runtimeGameObjectList.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ If all you want is to do something one-off when the game first loads, you don't even need the instance manager, you can just store a reference to the GameObject and change it that way. \$\endgroup\$ – DisturbedNeo Jul 4 '16 at 15:49
1
\$\begingroup\$

When you instantiate a prefab with Instantiate, you receive a reference to that object which you can then pass to where it is needed.

Alternatively, you can search for an object in the scene by its name with Find or by a tag with FindObjectWithTag. But keep in mind that these are not very fast (especially on larger scenes), so you should only do it once and save the result in a variable.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 25 seconds late..... damn \$\endgroup\$ – Uri Popov Jul 4 '16 at 9:26
1
\$\begingroup\$

you can use on of the following :

GameObject.Find("name of object");
GameObject.FindGameObjectWithTag("name of the tag of the object")

or alternatively you can just keep the reference to the instantiated game object after you create it.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does it matter whether the object is (Clone)? for "GameObject.FindGameObjectWithTag" \$\endgroup\$ – MMon Jul 4 '16 at 11:05
  • \$\begingroup\$ no. As log as the proper tag is set during instantiation. \$\endgroup\$ – Uri Popov Jul 4 '16 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.