- Home /
Instantiate inside foreach loop
Hello all! This is my first time using Unity, and I've run into quite a bugger trying to instantiate a prefab into UI. Everything works as it should when I have the instantiate line commented out, however when I attempt to run the instantiate command it stops the foreach loop and does not continue to run it for the other objects. For example, inside the loop is code that will prevent game objects from falling out of view, however they will fall once the instantiate function is called. uidListOS is a list that records all objects on screen.
GameObject[] allDragables;
allDragables = GameObject.FindGameObjectsWithTag("dragable");
foreach(GameObject obj in allDragables){
string objName = obj.name;
Vector3 v = obj.transform.GetComponent<Rigidbody2D>().velocity;
if (obj.activeInHierarchy){
//In Bounds
if (cam.WorldToViewportPoint(obj.transform.position).y <= 1.05){
if (uidListOS.Contains(objName) == false){
//destroyDistBox(objName);
writeToConsole("Back On screen; Only called once");
uidListOS.Add(objName);
}
}
//Upper Bound
if (cam.WorldToViewportPoint(obj.transform.position).y > 1.05){
if (uidListOS.Contains(objName)){ //Just went off screen
createDistBox(objName); //contains instantiate func
uidListOS.Remove(objName);
}
else
{ //Remaining off screen
updateDistBox(obj.name.ToString());
}
}
.......
And the function containing instantiate...
void createDistBox(string objId){
writeToConsole("Object " + objId.ToString() + " just off screen");
string _boxName;
GameObject box;
_boxName = objId + "box";
box = (GameObject)Instantiate(uiPrefab);//<--Issue
box.transform.SetParent(GameObject.Find("Canvas").transform, false);
box.name = _boxName;
}
Answer by AurimasBlazulionis · Dec 26, 2016 at 10:21 PM
Check the console for errors. Probably you haven't attached the prefab. Also, NEVER EVER user GameObject.Find in loops.
I'm compiling to android, so I have my own output on a basic onscreen console. That being said, there are no errors on the console. As for the GameObject.Find, what is an alternative?
Your answer
Follow this Question
Related Questions
Foreach loop wont run completely 3 Answers
Is having a "break" in a "foreach" loop that is itself inside a "for" loop breaking both loops? 3 Answers
Instantiate for loop skips some objects 1 Answer
Why is there a difference between script and in-game sequence of a script loop? 1 Answer
Unity Freezing 1 Answer