I have a script that is spawning treasure in random locations. I want the script to detect if a treasure has been placed, then save that placed position in a list. Once i spawn the next treasure, I then check if the treasure is too close to the previous placed treasures that are stored in the list. Im currently recieving an index out of bounds exception due to the "currentTreasureAmt" int not updating within the loop.
Heres the script so far
//used to determine if treasures are spawned too close
public float FindClosestTreasure()
{
GameObject[] TreasureList;
TreasureList = GameObject.FindGameObjectsWithTag("treasure");
GameObject closest = null;
float distance = Mathf.Infinity;
foreach (GameObject treasure in TreasureList)
{
Vector3 diff = treasure.transform.position - TreasureList[currentTreasureAmt].transform.position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = treasure;
distance = curDistance;
t++;
}
}
return distance;
}
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);
//Shoot the raycast in a random direction
if (Physics.Raycast(new Vector3(randomX, r.bounds.max.y + 5f, randomZ), -Vector3.up, out hit))
{
Vector3 RandomPos = hit.point;
if(FindClosestTreasure() > 5 && currentTreasureAmt < TotalTreasure)
{
Instantiate(TreasurePrefab, hit.point, Quaternion.identity);
currentTreasureAmt += 1;
Debug.Log(currentTreasureAmt);
Debug.Log("valid spawn");
}
if(FindClosestTreasure() < 5 && currentTreasureAmt < TotalTreasure)
{
Instantiate(TreasurePrefab, hit.point, Quaternion.identity);
Debug.Log("too close!");
currentTreasureAmt -= 1;
}
}
}
}
}
↧