- Home /
Hi , whats a way i can instantiate a prefab list randomly but make sure at least one of the prefabs is a certain chosen one?
Here is what i've got at the moment. This is used to instantiate a wall of object but i want at least one of them to always be a gap which could be prefab 7 for example.,
Just use an Array and assign the gameObjects in the inspector
No need to have references to each prefab and then adding to a list.
Could you be more specific? I don't quite understand the situation.
If you want to randomly instantiate, then your approach is good. How many objects do you want to instantiate? Could you provide an example?
Also, as @$$anonymous$$ mentioned, you should really use an array of GameObjects.
public GameObject[] prefabs; // This can be assigned through the inspector
int prefabIndex = UnityEngine.Random.Range(0, prefabs.Length - 1);
Instantiate(prefabs[prefabIndex], transform.position, Quaternion.identity);
To be more specific i have a row of spawn points where the prefabs are instantiated from individually. I used to have certain patterns that were randomly chosen from but i decided to make it that each spawn point randomized the prefab it chooses individually. So back to the question, is there a way i can make it so that in that row of 5 prefabs spawned how can i make it so that there is always at least one gap in the wall. Thankyou
Answer by KoenigX3 · Mar 10, 2021 at 07:46 PM
In this case, you need a script that controls all of the instantiating.
If you are using one global script that instantiates at these spawn points, then you should make a list of the indices that were chosen randomly, then check if it contains the index of the 'gap', and if it does not, you can select one of the spawn points randomly to generate a gap.
public Transform[] spawnPoints;
public GameObject[] prefabs;
const int gapIndex = 0;
void Start()
{
List<int> usedIndices = new List<int>();
for (int i = 0; i < spawnPoints.Length; i++) usedIndices.Add(UnityEngine.Random.Range(0, prefabs.Length));
if (!usedIndices.Contains(gapIndex)) usedIndices[UnityEngine.Random.Range(0, usedIndices.Count)] = gapIndex;
for(int i = 0; i < spawnPoints.Length; i++) Instantiate(prefabs[usedIndices[i]], spawnPoints[i].position, Quaternion.identity);
}
Note: my mistake, you don't have to use Count - 1, because the second parameter is exclusive.
@KoenigX3 worked exactly as i wanted thankyou very much!