[英]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.