- Home /
Comparing Vector 3 position to a list of vector 3 positions
I have a script that is generating random treasure locations in my scene. I am basically assigning a gameobject as the "treasure spawn zone" and anything within its bounds is a valid spawn point.
My script was working fine but I had issues where treasure were spawning too close to each other. So i have been attempting a solution and im getting some undesired results. For some reason I am having multiple treasures spawn in the exact same spot. I beleive I am comparing the list of vector3 correctly, and my debug for getting the distance is returning correct numbers. Anyone see something that Im missing?
void CreateRandomTreasure()
{
//Create a loop that will instantiate X amounts of Treasure
//Assign them to a random location based on the TreasureSpawnZone
for(int i = 0; i < TotalTreasure; i++)
{
//The raycast determines the random position
RaycastHit hit;
//Spawn "TotalTreasure" amounts of treasure
if(currentTreasureAmt <= TotalTreasure)
{
//Assign a random location within the Treasure Spawn zone
randomX = Random.Range(r.bounds.min.x, r.bounds.max.x);
randomZ = Random.Range(r.bounds.min.z, r.bounds.max.z);
if (Physics.Raycast(new Vector3(randomX, r.bounds.max.y + 5f, randomZ), -Vector3.up, out hit))
{
//Debug.Log(hit.point);
//Run another loop to check if the treasure spawn position is too
//close to another treasure that has already been spawned
for(int t = 0; t < TreasurePositions.Count; t++)
{
if(Vector3.Distance(hit.point, TreasurePositions[t]) > 3)
{
//Spawn a treasure object on that random location
Instantiate(TreasurePrefab, hit.point, Quaternion.identity);
currentTreasureAmt += 1;
TreasurePositions.Add(hit.point);
Debug.Log(Vector3.Distance(hit.point, TreasurePositions[t]));
}
}
}
}
}
}
I would guess my error is on line 23, I dont think I am correctly cycling through the entire list of TreasurePositions, but im not sure how to to fix that
Your answer
Follow this Question
Related Questions
Weird issue with List and for loop. 1 Answer
Outputting data to CSV file from multiple lists at specific Headers in the CSV? 0 Answers
Comparing each random element in an array with each other element 3 Answers
Affect every object in array. 1 Answer
Instantiate random prefab from folder using Resources.LoadAll 2 Answers