我试图创建一个简单的产卵器和一些延迟后,产卵僵尸。我为僵尸的数量设置了限制,但这不起作用,因为创建了12个僵尸,而不是10个。我可以通过在lenght <= max-2上替换lenght <= max-2来修复它,但是,我不知道问题的根源是什么。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
// Start is called before the first frame update
GameObject zombie;
bool condition;
public int max;
int lenght;
void Start()
{
zombie = Resources.Load("Prefabs/Zombie") as GameObject;
max = 10;
condition = true;
}
// Update is called once per frame
void Update()
{
GameObject[] zombies = GameObject.FindGameObjectsWithTag("Zombie");
lenght = zombies.Length;
Debug.Log(lenght);
if (condition && lenght <= max)
{
StartCoroutine(Spawn());
}
}
private IEnumerator Spawn()
{
condition = false;
while(lenght <= max){
yield return new WaitForSeconds(1);
Instantiate(zombie);
}
condition = true;
}
}发布于 2020-05-01 20:23:43
“问题的根源”是您的IF语句,它们都有小于或等于(=<)运算符,这意味着当它超过10的时候就会停止,这会产生一个额外的僵尸。只使用小于(<),确保如果数字为10,则停止,因为10不小于10。
https://stackoverflow.com/questions/61549757
复制相似问题