C# Instantiate multiple objects at unique positions within a set range
For a game I am working on in my free time. C#
Lets just say that I have a Box that is being Instantiated, more specifically a random box in a group called "groups" and it is being instantiated in a random location within a range though the following.
public class Spawner : MonoBehaviour {
public GameObject[] groups;
public int[] randomLocation = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
public void spawnNext() {
int i = Random.Range(0, groups.Length);
int s = Random.Range(0, randomLocation.Length);
Instantiate(groups[i],
new Vector3(randomLocation[s], 14, 0),
Quaternion.identity);
}
}
Now this portion works perfectly fine, the random object in the group is instantiated correctly within the mentioned range, but what I need to do specifically is Instantiate X amount of Box's within that range and each one being at a unique position so that there is no overlap. Furthermore the box's spawn location needs to be random every time spawnNext() is called and the amount of box's that are being spawned needs to be easily edited.
So what would be the best way to go about this?
Answer by toddisarockstar · Jul 31, 2016 at 03:04 AM
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
public string usedlocations=" ";
public int boxcount;
public GameObject[] groups;
public int[] randomLocation = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
public void spawnNext() {
boxcount = 3;
while(boxcount>0){boxcount--;
int i = Random.Range(0, groups.Length);
int s = Random.Range(0, randomLocation.Length);
while(usedlocations.Contains(" "+s)){s = Random.Range(0, randomLocation.Length); }
usedlocations=usedlocations+" "+s;
Instantiate(groups[i],
new Vector3(randomLocation[s], 14, 0),
Quaternion.identity);
}}}
Thank you Todd, this works perfectly and so much sleeker than what I was thinking of.