繁体   English   中英

实例化 Unity 2D

[英]Instantiating Unity 2D

我制作了一个脚本,应该每 1 秒产生一个敌人。 但是,一秒钟后它会产生数百个并且不会停止。

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;
    }
}

在您的Spawn协程中使用 while 循环,并在Start启动它,以便它只运行一个实例:

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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM