Find instantiated prefab by name
I have three game objects with triggers (lets call them buttons) that uses the same script. When the buttons are triggered, they instantiate a prefab (different prefabs from each button using a public variable.) Now, I want the script to check if the instantiated prefab already exists in the scene. But since the prefab has now added "(Clone)" to the end of it's name, the script can't find it.
public GameObject objectToSpawn;
void OnTriggerEnter(Collider other)
{
if (GameObject.Find("objectToSpawn") == null)
{
//Do stuff (includes instantiate prefab)
}
else if (GameObject.Find("objectToSpawn") != null)
{
//Do other stuff
}
}
So the problem is that the script always executes "Do stuff", even when the prefab clone exists in the scene. I dont' want to refer to the prefab as "prefabname(Clone)" or refer to a specific tag, because then the script won't work with the other buttons that instantiate different prefabs. It needs to refer to the public variable.
Answer by EWFilm · Sep 21, 2017 at 07:53 AM
Thanks for your replies, but I managed to solve it. Instead of using this:
(GameObject.Find("objectToSpawn")
I used this:
(GameObject.Find(objectToSpawn.name + "(Clone)")
So instead of looking for the string "objectToSpawn", which doesn't exist, it finds the name via the public variable and adds "(Clone)" to the end of it.
exact same solution as $$anonymous$$e. feeling robbed :)
Well, the thing about your solution is that there is no object called "objectToSpawn", so trying to find that string won't work. objectToSpawn is just the name of the public variable. Thanks anyway :)
I know that. But that was the name you used in your OP so I used it for clarity of reference.
Answer by ElFab · Sep 20, 2017 at 02:56 PM
I'm new user of unity, so i'll not be a great help... but while waiting for some more answers i'll try to give you some way to look at. You must have an overall class that keep track of your objects or, you must set the name or the tag (i don't know how is possible to search for an existing instance in the scene from name or tag) at the moment you create it, you must look at the button class in the documentation i'm sure you can do something like this:
Button bt;
_bt = getbuttonByName("newName");
if (!_bt)
{
bt = newButton();
bt.setName("newName");
}
Answer by unit_nick · Sep 20, 2017 at 03:19 PM
I believe this may work
else if (GameObject.Find("objectToSpawn(Clone)") != null)