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 *= 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*.transform.position = Pos;_
_ }_
_}*_
In other words, you (the OP) wrote a regular boring infinite loop. There's nothing special about the
– Owen-Reynoldsbreakstatement.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!
– Alex_K98Jeffom, how would you suggest to overcome 'j < i' that you think causing the freeze? Thanks in advance.
– Alex_K98You could change the while condition, or make a flag for a better check to break out of the while loop.
– JeffomI 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 minimum 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.
– Bonfire-Boy