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;
}