i’m trying to get a script to work that clones and places X amount of cubes from a prefab. Originally i had it set up to place a cube in a random position and if it detects a collision it runs the randomization again until all cubes are randomly placed. I’m trying to improve this by having the script text if there’s a collision in the random position and place the cube there if it doesn’t find a collision. That way when i run the game there isn’t that brief moment where all the cubs are jumping around trying to find a random position with no collisions. My Problem is my Current script i have just causes unity to not respond and then i have to restart unity.
I’m pretty sure iv’e either created and infinite while loop or i have a hunch it may have something to do with either how iv’e cloned or am running my collision test because when i ran the collision test as an if statement and set the cubes to a diferant color before placing it if it found a collision all my cubes were placed with a different color regardless of if there was a collision. here’s my script any help or advice would be really appreciated
public class randomtest : MonoBehaviour {
public float minX;
public float maxX;
public float minZ;
public float maxZ;
void Start()
{
randomize();
}
void randomize()
{
var newpos = new Vector3(Random.Range(minX, maxX), 1, Random.Range(minZ, maxZ));
var checkResult = Physics.OverlapSphere(newpos, 1);
while (checkResult.Length != 0)
{
// Renderer rend = GetComponent<Renderer>();
// rend.material.shader = Shader.Find("Specular");
// rend.material.SetColor("_SpecColor", Color.green);
newpos = new Vector3(Random.Range(minX, maxX), 1, Random.Range(minZ, maxZ));
checkResult = Physics.OverlapSphere(newpos, 1);
}
gameObject.transform.position = newpos;
}
}