george
george

Reputation: 21

Instantiating Unity 2D

I made a script that is supposed to spawn an enemy every 1 second. However, after one second it spawns hundreds and doesn't stop.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PSpawner : MonoBehaviour
{
    public Transform spawny;
    public Transform p;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        StartCoroutine("Spawn");
    }
    public IEnumerator Spawn()
    {
        yield return new WaitForSeconds(1);
        Instantiate(spawny, p.position, Quaternion.identity);
        yield return null;
    }
}

Upvotes: 1

Views: 188

Answers (1)

Ruzihm
Ruzihm

Reputation: 20249

Use a while loop in your Spawn coroutine, and start it in Start so that there is only ever one instance of it running:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PSpawner : MonoBehaviour
{
    public Transform spawny;
    public Transform p;
    public bool doSpawn;

    // Start is called before the first frame update
    void Start()
    {
        doSpawn = true;
        StartCoroutine("Spawn");
    }

    public IEnumerator Spawn()
    {
        WaitForSeconds wait = new WaitForSeconds(1);

        while (doSpawn)
        {
            yield return wait;
            Instantiate(spawny, p.position, Quaternion.identity);
        }
    }
}

Upvotes: 1

Related Questions