- Home /
Random.Range when instantiating things at start freezes the game
Hey i got an problem with instantiating prefabs (trees, rocks, bushes) on startup. I have a script to do it:
using UnityEngine; using System.Collections;
public class raySpawn : MonoBehaviour {
public GameObject[] propy = new GameObject[30]; //Array of prefabs
private Vector3 origin;
private int index = 0;
private bool czyIndexPoprawny = false; //currently unused
// Use this for initialization
void Start () {
origin = gameObject.transform.position;
RaycastHit hit;
for(int i = 0; i < 4000; i++)
{
Ray linia = new Ray(gameObject.transform.position, new Vector3(Random.Range(-1000,1000), -500, Random.Range(-1000,1000)));
if(Physics.Raycast(linia,out hit) && hit.transform.tag == "ZaczepBudowy") //If it hits terrain
{
if(hit.point.y > 24) //So things wont generate at sea level
{
index = Random.Range(0,12);
//if(index != null)
Instantiate(propy[index],hit.point,Quaternion.identity);
}
}
else
i--;
//Debug.Log(Random.Range(0,11).ToString()); I checked if its something horribly wrong with Random.Range itself
}
}
}
Theres currently 12 objects in array (0 to 11). I dont know why, but Random.Range(X,Y) includes the X but excludes the Y, so i have to add one digit to it. When i put 10 as a Y, it works (only 9 of 12 will spawn) but when i put 11 as Y, the game freezes horribly and makes F and S in FPS switch place. (Seconds per Frame ¯_(ツ)_/¯ ). I seek an solution for this. I checked if one prefab of those is causing a massive lag, but i found that not one of the prefabs is causing the problem. Unaccounted takes up to 95% of memory in the profiler. I dont know why
Answer by Raresh · Nov 13, 2016 at 09:05 AM
The documentation says clearly, that Random.Range is max inclusive only for FLOATS. https://docs.unity3d.com/ScriptReference/Random.Range.html
Answer by tanoshimi · Nov 13, 2016 at 10:42 AM
Your solution to your infinite loop is to remove the following line, which causes the for loop counter to not increment:
else
i--;
It executes only if Physics.Raycast AND the hit object tag != "ZaczepBudowy" fails.
Yep, and that test is failing, which is why you're getting stuck forever.
It doesnt fail. If it would, it wouldnt spawn things on the map.