- Home /
Question by
soggi92 · May 08, 2021 at 04:16 PM ·
unity 2dspawning problems
HI I'm having a problem with spawning objects
I've been playing around with some YouTube videos for object spawning, but I'm having a bit of an issue. When I run the game, the whole screen gets crowded with the objects, and I have no idea why its happening. Can anyone tell me why this is occurring? Below is the code that i'm using, i have also posted an image of the outcome.
Thanks
[SerializeField]
private float xLimit;
[SerializeField]
private float[] xPositions;
[SerializeField]
private GameObject[] emojiPrefabs;
[SerializeField]
private Wave[] wave;
private float currentTime;
List<float> remainingPositions = new List<float>();
private int waveIndex;
float xPos = 0;
int rand;
void Start()
{
currentTime = 0;
remainingPositions.AddRange(xPositions);
}
void Update()
{
SelectWave();
}
void SpawnEnemy(float xPos)
{
int r = Random.Range(0, 2);
Instantiate(emojiPrefabs[r], new Vector3(xPos, transform.position.y, 0), Quaternion.identity);
}
void SelectWave()
{
remainingPositions = new List<float>();
remainingPositions.AddRange(xPositions);
waveIndex = Random.Range(0, wave.Length);
currentTime = wave[waveIndex].delayTime;
if(wave[waveIndex].spawnAmount == 1)
{
xPos = Random.Range(-xLimit, xLimit);
} else if(wave[waveIndex].spawnAmount > 1)
{
rand = Random.Range(0, remainingPositions.Count);
xPos = remainingPositions[rand];
remainingPositions.RemoveAt(rand);
}
for (int i = 0; i < wave[waveIndex].spawnAmount-1; i++)
{
SpawnEnemy(xPos);
rand = Random.Range(0, remainingPositions.Count);
xPos = remainingPositions[rand];
remainingPositions.RemoveAt(rand);
}
}
}
[System.Serializable]
public class Wave
{
public float delayTime;
public float spawnAmount;
}
capture.jpg
(75.6 kB)
Comment
Best Answer
Answer by GSGregory · May 08, 2021 at 04:27 PM
You seem to be setting a delay time and current time, but not using either in an if statement, nor counting time.
Right now, on each frame you call SelectWave, and it spawns things.
Your answer
![](https://koobas.hobune.stream/wayback/20220613033458im_/https://answers.unity.com/themes/thub/images/avi.jpg)