Hi all, I have a need to locate a certain gameobject in the scene at runtime.
I have a whole bunch of doors that are all from instantiated prefabs, but when they are created they are given a unique door number. Basically, I need to find that number in script and assign it to a target.
Here are excerpts of my scripts:
GameObject[] doors;
doors = GameObject.FindGameObjectsWithTag("Door");
Ok, so now I have an array of Doors, that all have the script “Door Controller” on them. There is a unique int called “Door Number”.
So, my question is how can I find the gameobject in this array, that has a certain door number?
Any help would be greatly appreciated
There are several ways to do it, but the most intuitive way (for me) is to use something called a foreach loop!
Here’s what I would do.
public GameObject doorIAmAccessing; //Declare this outside the function (at the top of script)
int numberIAmLookingFor = 9; //Define the door number we want. This can be done in many ways.
foreach (Gameobject door in doors){ //For each (GameObject) door in the list of doors...
int doorNumber = door.GetComponent<scriptOnTheDoor>().doorNumber; //doorNumber is the number on the door's script.
if(doorNumber == numberIAmLookingFor){ //If the door number on said door is the number I'm looking for...
doorIAmAccessing = door; //This is the door!
}
} //If it isn't, the foreach loop will automatically run until it gets to the end of the list.
if all the doors have the script on them maybe adding a public int variable inside your script called doorNumber or something like that and assign the number for each door in the editor
then a loop through the doors array and a check for that variable should work
GameObject[] doors;
doors = GameObject.FindGameObjectsWithTag("Door");
GameObject tempDoor;
foreach(object door in doors) {
if(door.GetComponent<SCRIPT_NAME>().doorNumber == DOOR_INT {
tempDoor = door;
break;
}
}
however, there’s probably a more efficient/better way…i’m still learning Unity myself