I am trying to spawn a random enemy in a spawn area which is defined by a collider, and I am using unity’s Random function to choose a random prefab enemy to instantiate and then a random position within the collider’s bounds to instantiate them at. However, whenever I run the game, the results are always the same and the same enemies always spawn at the same positions, as shown in the screenshot below.
The enemy prefab “Crawler” always spawns near the top middle of the screen, and the “zombie” always spawns near the top right. Upon spawning, the enemies move towards the player (who is in the centre of the screen).
Whenever I run the game, the same results always happen, and the three other enemy types never get spawned, and the positions which the “Crawler” and “Zombie” spawn at are always in the exact same positions.
The code used to spawn the enemies is below, the collider is a 2D box collider which is the size of the brown area.
I am unsure what I have done wrong to make the random always the same between plays.
The script which is used to spawn in the enemies is below, and I am unsure whether it is a script error or perhaps something else? Perhaps I am misunderstanding how to use random?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public float spawnRate;
public Collider2D spawnArea;
public GameObject[] enemyPrefabs;
public GameObject wormPrefab;
public GameObject zombiePrefab;
public GameObject spiderBeetlePrefab;
public GameObject crawlerPrefab;
public GameObject spiderPrefab;
[Range(0f, 1f)]
public float wormChance;
[Range(0f, 1f)]
public float zombieChance;
[Range(0f, 1f)]
public float spiderBeetleChance;
[Range(0f, 1f)]
public float crawlerChance;
[Range(0f, 1f)]
public float spiderChance;
private void Start()
{
InvokeRepeating(nameof(SpawnEnemy), 1f, spawnRate);
}
private void SpawnEnemy()
{
GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];
float random = Random.value;
if (random < wormChance)
{
enemyPrefab = wormPrefab;
Debug.Log("Worm");
}
else if (random < zombieChance)
{
enemyPrefab = zombiePrefab;
Debug.Log("Zombie");
}
else if (random < spiderBeetleChance)
{
enemyPrefab = spiderBeetlePrefab;
Debug.Log("SpiderBeetle");
}
else if (random < crawlerChance)
{
enemyPrefab = crawlerPrefab;
Debug.Log("Crawler");
}
else if (random < crawlerChance)
{
enemyPrefab = spiderPrefab;
Debug.Log("Spider");
}
Vector2 position = new Vector2();
position.x = Random.Range(spawnArea.bounds.min.x, spawnArea.bounds.max.x);
position.y = Random.Range(spawnArea.bounds.min.y, spawnArea.bounds.max.y);
Quaternion rotation = Quaternion.identity;
Instantiate(enemyPrefab, position, rotation);
}
}
I have searched around a bit but could find no similar problems to what I am experiencing.
If any additional info is needed then please ask,
Thanks.
