- Home /
'brake' statement makes Unity hang ?
Can someone explain why this code makes Unity hang?
This tries to find a non-intersecting position for objects generated. 'prefab' is a common Unity sphere which size is set to (50,50,50). Default 'SphereCollider' is set to 'isTrigger' (just in case).
I suspect 'break' call being a problem, because I have experienced strange behavior of 'return' call.
Important note: CalcPositions() works without 'hang' problem in other engine!!!
Any help would be much appreciated.
Here is the code:
public GameObject prefab; //sphere of size (50,50,50)
GameObject[] go; //array of these spheres
int Count = 3; //size of array
float ObjectRadius = 50; //scalar of sphere size
float SceneRadius = 250; //area of position value generation
Vector3 pos = new Vector3(0,0,0);
void Awake () {
go = new GameObject[Count]; //init of array
Generate (); //generating objects
CalcPositions (); //calculating positions
}
void Generate () {
for (int i = 0; i < Count; i++) {
Quaternion rot = Quaternion.identity;
go[i] = Instantiate (prefab, pos, rot) as GameObject;
}
}
void CalcPositions () {
int j = 0;
for (int i = 0; i < Count; i++) {
Pos.x = Random.Range (-SceneRadius, SceneRadius);
Pos.y = 0; Pos.z = 0;
while (j < i) {
for (j = 0; j < i; j++) {
Vector3 tempPos = go[j].transform.position;
if (Vector3.Distance(tempPos, Pos) < ObjectRadius) {
break;
}
}
Pos.x = Random.Range (-SceneRadius, SceneRadius);
}
go[i].transform.position = Pos;
}
}
Answer by Jeffom · Mar 25, 2015 at 01:20 PM
the break statement is breaking out of the for before j < i, and that causes the code to freeze.
In other words, you (the OP) wrote a regular boring infinite loop. There's nothing special about the break
statement.
Gentlemen, the thing is that CalcPositions function hangs randomly. It can generate non-intersecting positions nicely, but next time it can run into 'hang' even if there is triple space reserve to find correct position. That is the problem and weirdness!
Jeffom, how would you suggest to overcome 'j < i' that you think causing the freeze? Thanks in advance.
You could change the while condition, or make a flag for a better check to break out of the while loop.
I take the points raised already, and the while thing doesn't look like a great way of doing this. But it's still not clear to me why it's not working. There should be enough space for it to be able to randomly find 3 positions that aren't that close to each other (although shouldn't the $$anonymous$$imum distance be 2*ObjectRadius?).
I would add some logging, in particular to show what the values of i, j, and Pos are when it detects an object too close to Pos.
Your answer
Follow this Question
Related Questions
Game random freeze / hang up / stuck 0 Answers
Unity Keeps Freezing on Play 5 Answers
Unity 4.1 hangs/freezes on startup (Mac) 0 Answers
Scripts freezes game for a few seconds after build. 1 Answer