[英]Instantiating Unity 2D
I made a script that is supposed to spawn an enemy every 1 second.我制作了一个脚本,应该每 1 秒产生一个敌人。 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;
}
}
Use a while loop in your Spawn
coroutine, and start it in Start
so that there is only ever one instance of it running:在您的
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.