Search code examples
c#loopsunity-game-enginecountdown

How to check whether my countdown hits 0 in my function?


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

Reference to my game

I want to code it so that when PlayerTurn() is called, I want the function to check whether the countdown hits 0. When it does hit 0, it would decrement the number of hearts player 1 has.

However I can only place that condition in my Void Update() method as I cannot place the condition inside my Void PlayerTurn(), which is where I want it to be.

For example...

void PlayerTurn()

dialogueText.text = "Player 1's turn"

if currenttime is 0, decrement player 1's number of hearts, state = battlestate.player2turn and Player2Turn()

Then if player 2 runs out of time, then it would switch back to player 1 and then back to player 2 and so on (loop).


Solution

  • Modified Void Update()...

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