首页 > 解决方案 > 如何检查我的倒计时是否在我的函数中达到 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,依此类推(循环)。

标签: c#loopsunity3dcountdown

解决方案


修改后的无效更新()...

    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;
        }
    }

推荐阅读