我看不到无限循环,但我的游戏仍然死机
I can't see an infinite loop but my game still freezes
我有一些 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);
}
}
我有一些 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);
}
}