【发布时间】:2016-03-20 10:24:03
【问题描述】:
我有一些 Unity c# 游戏中的敌人的代码。该代码有一个降低生命值的函数和一些连接到触发器的代码,该触发器使用Invoke() 调用该函数。 Invoke 方法存储在 while 循环中,以便在运行状况大于 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");
}
}
}
【问题讨论】:
-
你在哪里分配 Enemy.Damage?我看到您已将 2.0f 传递给 Invoke,但没有将 Enemy.Damage 分配给此参数。
-
Enemy.Damage 是一个名为 damage 的公共静态浮点数,位于另一个名为 Enemy 的脚本中
-
听起来您需要使用调试器并花时间逐步检查并评估所有变量以查看是否可以查明问题
-
无限循环不会导致程序冻结,而是崩溃。冻结是由循环时间过长引起的,通常在 1 线程应用程序中(在循环完成之前无法更新 GUI)。解决方案很简单:多线程(嗯……或者使循环更快)。
-
while 循环看起来很可疑,因为它会导致你的角色在碰到敌人时死亡。此外,
2.0f意味着您的调用被延迟(see the docs),因此 while 循环只是不断地将函数调用排队,而不会真正降低玩家的健康状况(因此您会得到无限循环)
标签: c# unity3d while-loop infinite-loop freeze