c# - 如何检查我的倒计时是否在我的函数中达到 0?
问题描述
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum BattleState { START, PLAYERTURN, PLAYER2TURN, WON, LOST }
public class BattleSystem : MonoBehaviour
{
public GameObject playerPrefab;
public GameObject player2Prefab;
public Transform playerBattleStation;
public Transform player2BattleStation;
public Text dialogueText;
public Health playerHealth;
public Health player2Health;
public BattleState state;
public float currentTime = 0f;
float startingTime = 15f;
public Text countdownText;
void Start()
{
state = BattleState.START;
StartCoroutine(SetupBattle());
currentTime = startingTime;
}
void Update() //countdown
{
currentTime -= 1 * Time.deltaTime;
countdownText.text = currentTime.ToString("0");
if (currentTime <= 0)
{
currentTime = 0;
Debug.Log("countdown hits 0");
}
}
IEnumerator SetupBattle()
{
dialogueText.text = "Get ready " + playerUnit.unitName + "!";
yield return new WaitForSeconds(5f);
state = BattleState.PLAYERTURN;
PlayerTurn(); //player 1's turn
}
void PlayerTurn()
{
dialogueText.text = playerUnit.unitName + "'s turn.";
}
}
我想对其进行编码,以便在调用 PlayerTurn() 时,我希望该函数检查倒计时是否达到 0。当它确实达到 0 时,它会减少玩家 1 拥有的红心数量。
但是,我只能将该条件放在我的 Void Update() 方法中,因为我无法将条件放在我想要的 Void PlayerTurn() 中。
例如...
无效的球员转()
dialogText.text = "玩家 1 的回合"
如果 currenttime 为 0,则减少玩家 1 的心数,state = Battlestate.player2turn 和 Player2Turn()
然后如果玩家 2 用完时间,那么它将切换回玩家 1,然后再切换回玩家 2,依此类推(循环)。
解决方案
修改后的无效更新()...
void Update() //countdown
{
currentTime -= 1 * Time.deltaTime;
countdownText.text = currentTime.ToString("0");
if (currentTime <= 0 && state == BattleState.PLAYERTURN)
{
currentTime = 0;
playerHealth.numOfHearts = playerHealth.numOfHearts - 1;
state = BattleState.PLAYER2TURN;
Player2Turn();
currentTime = 10;
}
else if (currentTime <= 0 && state == BattleState.PLAYER2TURN)
{
currentTime = 0;
player2Health.numOfHearts = player2Health.numOfHearts - 1;
state = BattleState.PLAYERTURN;
PlayerTurn();
currentTime = 10;
}
}
推荐阅读
- cplex - CPLEX OPL 在运行 150 小时后崩溃
- emacs - 如何探索 Common Lisp 图像
- c++ - 将命令行参数传递给对象的最佳方法
- php - 数组返回我在 php 中预期的不同结果
- iphone - 使用 nuxt auth 和 django rest 框架 simple-jwt 登录 iPhone 时出现 401 错误
- python - 按分隔符拆分数字
- java - 如何在java中结合一秒和一分钟的时间
- amazon-web-services - AWS Network Load Balencer - 会话粘性不起作用
- react-native - 如何使 onchangetext 中的处理提交反应原生
- node.js - 当输入是经纬度数时,如何为 Odata Api 返回有效的 Edm.GeographyPoint?