I am trying to work on a script to spawn a gameobject at a random position between a range of positions but not too close to each other. It is spawning, just not correctly. It is spawning 2 sets of 12 random positions instead of just 1 set. Each set is following the correct range rules, however when the 2 sets are put together, they don’t follow the range rules and are overlapping. I am unsure where I went wrong with this script and would love to get some help with it.
Here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnTest : MonoBehaviour
{
public GameObject prefab;
public int wayPoints = 12;
public float minDist = 1f;
public List<Vector3> waypointPositions = new List<Vector3>();
void Start ()
{
FillList();
}
void FillList ()
{
for (int i = 0; i < wayPoints; i++)
{
while (waypointPositions.Count < wayPoints)
{
Vector3 randomPos = new Vector3(Random.Range(-2f, 2f), Random.Range(.5f, 4f), 0f);
bool isClose = false;
foreach (Vector3 wp in waypointPositions)
{
if (Vector3.Distance(wp, randomPos) <= minDist)
{
//Debug.Log("dist: " + Vector3.Distance(wp, randomPos));
isClose = true;
}
}
if (!isClose)
{
waypointPositions.Add(randomPos);
Instantiate(prefab, randomPos, prefab.transform.rotation);
break;
}
}
}
}
}
When putting wayPoints = 6, I get 18 actual wayPoints. When putting wayPoints to 12, I get 24 waypoints. When putting wayPoints to 24, I get 12 wayPoints.