Grendernaz
Grendernaz

Reputation: 23

Spawning enemies

I have 10 points in which I would like to spawn enemies on a 2d field. How would I place these objects into a list and then select one at random to spawn an enemy from?

I can create the list itself but cannot figure out a way to add the points into the list.

UPDATE

So I have figure out the problem I had originally and created the random spawn, as well as adding in a wave spawn that spawns enemies from every point after a certain number of single enemies have spawned.

I set a timer so that the level only last for a certain amount of time but when the timer runs out and I stop the coroutine, everything stops, even the bullets from the weapon that you fire. Does anybody see the issue in my code?

public class Spawn_Manager : MonoBehaviour
{
    [SerializeField]
    private GameObject _monsterPrefab;
    [SerializeField]
    private GameObject _enemyContainer;

    public static bool _stopSpawn = false;

    public GameObject[] SpawnPoints;
    public GameObject randomPoint;
    public GameObject WaveSpawn;

    // Start is called before the first frame update
    void Start()
    {
        SpawnPoints = GameObject.FindGameObjectsWithTag("Spawns");
        StartCoroutine(SpawnRoutine());

    }

    // Update is called once per frame
    void Update()
    {
        if (Timer.timeLeft <=0)
        {
            _stopSpawn = true;
        }
    }

    IEnumerator SpawnRoutine()
    {
        while (_stopSpawn == false)
        {
            for (int i = 0; i < StageMode.NumberToSpawn; i++)
            {
                randomPoint = SpawnPoints[Random.Range(0, SpawnPoints.Count())];
                GameObject newMonster = Instantiate(_monsterPrefab, randomPoint.transform.position, randomPoint.transform.rotation);
                newMonster.transform.parent = _enemyContainer.transform.parent;
                yield return new WaitForSeconds(StageMode.SpawnDelay);

                if (i == StageMode.SpawnCounter)
                {
                    for (int j = 0; j < StageMode.WavesToSpawn; j++)
                    {
                        for (int k = 0; k < SpawnPoints.Length; k++)
                        {
                            Instantiate(_monsterPrefab, SpawnPoints[k].transform.position, SpawnPoints[k].transform.rotation);
                        }
                    }
                    i = 0;
                }
            }
        }
    }
}

Upvotes: 0

Views: 220

Answers (1)

ERSUCC
ERSUCC

Reputation: 68

After you create the list, add the points in one by one like this:

points.Add(point1);
points.Add(point2);
...

or like this:

points.AddRange(new Vector2[] { point1, point2... });

Then you can pick a random one by indexing the list like this:

Vector2 randomPoint = points[Random.Range(0, points.Count)];

Upvotes: 2

Related Questions