- Home /
gameobject generates sometimes on previous position
Hello everyone, I'm testing a script which generates random blocks. This works good, but it sometimes generates the same position as previous blocks. Now I want to fix that.
Here is my code:
using UnityEngine;
using System.Collections;
public class TerrainGeneration : MonoBehaviour {
public GameObject Block;
private int totalBlocks;
void Start () {
for(totalBlocks = 0; totalBlocks < 100; totalBlocks++)
{
var xpos = Mathf.Round(Random.Range(-5.0F, 5.0F));
var zpos = Mathf.Round(Random.Range(-5.0F, 5.0F));
Instantiate(Block, new Vector3(xpos , 0, zpos), Quaternion.identity);
}
}
void Update () {
}
}
I've tried with some if statements but i could not get this to work. Has someone a idea how I can fix this?
Answer by robertbu · May 12, 2013 at 01:12 PM
The brute force approach is to repeatedly generate a random position and only use it if it meets a distance criteria. This question comes up from time to time on this list, so a Google search will find you examples. Here is one example:
http://answers.unity3d.com/questions/385857/instantiating-objects-at-random-positions-with-a-c.html
Took a bit closer look at the code at the link. He uses OverlapSphere(). For your use, you can call CheckSphere() and simplify things a bit.
Your answer
Follow this Question
Related Questions
Get position for each Gameobject (in array) ? 0 Answers
GameObject won't move to Transform Position 0 Answers
GameObject change Position after game started 1 Answer
Scrolling Sprite Object 0 Answers