Spawn unique objects from the array
Hello, i have 4 cubes - red, green, yellow, blue. I want spawner to instantiate 4 cubes at once next to each other, all of them must have different colors. Here is my code.
------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnScript : MonoBehaviour
{
public List<GameObject> Cubes;
public float TimeBetweenSpawn = 2f;
// Update is called once per frame
void Update()
{
if(TimeBetweenSpawn <= 0)
{
for(int i = 0; i < Cubes.Count; i++)
{
int rand = Random.Range(0, Cubes.Count);
GameObject Cube = Instantiate(Cubes[rand], transform.position, Quaternion.identity);
Cubes.Remove(Cube);
}
TimeBetweenSpawn = 2f;
}
else
{
TimeBetweenSpawn -= Time.deltaTime;
}
}
}
Would be very happy, if you give some hints or advices, i tried to search for the solutions in google, but it was unsuccessful. Thank you in advance.
What does not work with your current code? What is the current behaviour? The desired one?
Answer by Getsumi3 · Oct 04, 2019 at 11:37 AM
Check this answer: https://answers.unity.com/questions/486626/how-can-i-shuffle-alist.html
Try to shuffle your list before using it.
Example:
public void ShuffleMyList()
{
for (int i = 0; i < Cubes.Count; i++)
{
GameObject temp = Cubes[i];
int randomIndex = Random.Range(i, Cubes.Count);
Cubes[i] = Cubes[randomIndex];
Cubes[randomIndex] = temp;
}
}
void Update()
{
if (TimeBetweenSpawn <= 0)
{
ShuffleMyList();
for (int i = 0; i < Cubes.Count; i++)
{
Instantiate(Cubes[i], transform.position, Quaternion.identity);
}
TimeBetweenSpawn = 2f;
}
else
{
TimeBetweenSpawn -= Time.deltaTime;
}
}
Your answer
Follow this Question
Related Questions
List or Arrays, and how to randomize them. 1 Answer
How do you spawn a gameobject based on last object in array and limit that within a range? 1 Answer
Trying to program two buttons to appear when the player in my game dies 0 Answers
Only spawning power ups that the player wants in that game 1 Answer