我可以';我看不到无限循环,但我的游戏仍然冻结
本文关键字:我的 游戏 冻结 无限循环 我看 看不到 我可以 | 更新日期: 2023-09-27 18:26:55
我有一些Unity c#游戏中敌人的代码。该代码有一个降低运行状况的函数,还有一些代码连接到使用Invoke()
调用该函数的触发器。Invoke
方法存储在while循环中,以便在health大于0时执行。脚本如下。
我可以运行游戏,但每当敌人进入扳机时,游戏就会冻结。这通常是由于一个无限循环,但在我看来,它看起来是正确的。我有什么东西不见了吗?
using UnityEngine;
using System.Collections;
public class Base : MonoBehaviour {
public float Health = 100f;
public float AttackSpeed = 2f;
//If enemy touches the base
void OnCollisionEnter2D(Collision2D col){
Debug.Log ("Base touched");
if(col.gameObject.tag == "Enemy"){
while(Health > 0f){
Debug.Log ("Enemy attacking base");
//call attack funtion in x seconds
Invoke("enemyAttack", 2.0f);
}
}
}
//Enemy attack function that can be used with Invoke
void enemyAttack(){
Health -= Enemy.Damage;
Debug.Log ("Base health at: " + Health);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Load Lose Screen when Base health reaches 0
if (Health <= 0){
Application.LoadLevel("Lose Screen");
}
}
}
您的Invoke()
被反复调用,正在排队。你应该在这里使用协同游。
void OnCollisionEnter2D(Collision2D col){
Debug.Log ("Base touched");
if (col.gameObject.tag == "Enemy"){
if (Health > 0f){
Debug.Log ("Enemy attacking base");
StartCoroutine (enemyAttack ());
}
}
}
IEnumerator enemyAttack () {
while (Health > 0f) {
yield return new WaitForSeconds (2f);
Health -= Enemy.Damage;
Debug.Log ("Base health at: " + Health);
}
}