Hello, I did some research for spawning random objects but they didn’t seem not I wanted. For an example, I have a terrain and there is a specific locations that I want an object to spawn there.
Here is what I should do:
1.) There is more than 5 spawn locations and 1 or more objects that I want to randomly instantiate in this locations.
2.) Instantiated Random Objects should not have to spawn again in the same location point.
How do I achieve this? I really appreciate any help. Thanks.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SpawnObjects : MonoBehaviour {
//specify all gameobjects to spawn in editor
public GameObject SpawnableObjects;
//private non editable in editor
private Dictionary<Vector3, GameObject> _spawnedObjects = new Dictionary<Vector3, GameObject>();
private System.Random Rand = new System.Random();
//specify the spawn borders in editor
public Vector3 MinSpawnRange;
public Vector3 MaxSpawnRange;
void Start()
{
for(int i=0; i < SpawnableObjects.Length; i++)
{
Vector3 randPos = new Vector3(Rand.Next((int)MinSpawnRange.x, (int)MaxSpawnRange.x), Rand.Next((int)MinSpawnRange.y, (int)MaxSpawnRange.y), Rand.Next((int)MinSpawnRange.z, (int)MaxSpawnRange.z));
while (_spawnedObjects.Keys.Any(f => f.x == randPos.x && f.y == randPos.y && f.z == randPos.z))
{
randPos = new Vector3(Rand.Next((int)MinSpawnRange.x, (int)MaxSpawnRange.x), Rand.Next((int)MinSpawnRange.y, (int)MaxSpawnRange.y), Rand.Next((int)MinSpawnRange.z, (int)MaxSpawnRange.z));
}
Instantiate(SpawnableObjects*, randPos, Quaternion.identity);*
spawnedObjects.Add(randPos, SpawnableObjects*);
_}*
}
}