When I run this script Unity becomes unresponsive and won’t close. I additionally would find it helpful if somebody could share how I could terminate my code if it runs for too long.
The purpose of this script to randomly generate buildings ,insert buildings randomly selected from another array t the corners, and add a gap at the end of the row when the scene loads. I have created and assigned Unity tags: “building” and “cornerbuilding”. I have also created the tag “instance”
using UnityEngine;
using System.Collections;
public class buildingplace : MonoBehaviour {
public GameObject[] buildings;
public GameObject[] cornerBuildings;
public GameObject streetSpace;
private GameObject[] Instances;
//i= current instance
//r=current selector
private float addwidth;
private float distance=0f;
public float streetLen=20f;
void Start()
{
buildings = GameObject.FindGameObjectsWithTag ("building");
cornerBuildings = GameObject.FindGameObjectsWithTag ("cornerBuilding");
//TO DO: loopfor 25 blocks
for (int i = 0; distance<streetLen; i++)
{
int r= Random.Range(0, (buildings.Length));
float currentW = (buildings [r].GetComponent<Collider> ().bounds.size.z) * .5f;
//this if will place the first cornder building on the street
if(Time.realtimeSinceStartup==10f){
Debug.Log ("loop closed");
return;
}
if(i==0){
r = Random.Range(0, (cornerBuildings.Length));
Debug.Log(r);
Debug.Log(cornerBuildings.Length);
Debug.Log (buildings.Length);
GameObject frontCornerInst = Instantiate(cornerBuildings[r], new Vector3(0, 0, currentW), Quaternion.identity) as GameObject;
frontCornerInst.gameObject.tag = ("instance");
distance += currentW;
//place last corner building at transform.position.z=streetlen-currentW
GameObject backCornerInst = Instantiate(cornerBuildings[r], new Vector3(0, 0, streetLen-currentW), Quaternion.identity) as GameObject;
backCornerInst.gameObject.tag = ("instance");
GameObject streetSpaceInst = Instantiate(streetSpace, new Vector3(0, 0, streetLen+currentW), Quaternion.identity) as GameObject;
streetSpaceInst.gameObject.tag = ("instance");
}
else{
while(buildings [r].GetComponent<Collider> ().bounds.Intersects(buildings [r].GetComponent<Collider> ().bounds));
addwidth = (Instances[i-1].GetComponent<Collider>().bounds.size.z)*.5f;
distance+=addwidth+currentW;
GameObject instance = Instantiate(buildings[r], new Vector3(0, 0, distance), Quaternion.identity) as GameObject;
instance.gameObject.tag = ("instance");
Debug.Log (addwidth +"_"+ currentW +"_"+ distance);
}
Instances = GameObject.FindGameObjectsWithTag ("instance");
}
foreach(GameObject building in buildings){
building.SetActive(false);
}
foreach (GameObject cornerBuilding in cornerBuildings) {
cornerBuilding.SetActive (false);
}
}
}