Search Unity

Question How do I enable a script/bool with a button?

Discussion in 'Scripting' started by tiagosparkz, Jul 1, 2022.

  1. tiagosparkz

    tiagosparkz

    Joined:
    Jul 1, 2022
    Posts:
    7
    Beginner so I might have missed something obvious.

    https://gamedevbeginner.com/how-to-make-countdown-timer-in-unity-minutes-seconds/#timer

    Currently have one script which I followed from GameDevBeginner (Link above) website to make a countdown timer, with the modifications being:
    • The amount of time itself
    • Setting the timer back to 5 on the 2nd else (which I assume runs every time the script is at the end)
    • Extra progress float that I tried to make go up over time ( to link with the progress bar to represent the time going down ) which I think is working fine?
    ----------
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    public class Timer : MonoBehaviour
    {
    public float progress = 0;
    public float timeRemaining = 5;
    public bool timerIsRunning = false;
    public Text timeText;
    private void Start()
    {

    }
    void Update()
    {
    if (timerIsRunning)
    {
    if (progress < 5)
    {
    progress += Time.deltaTime;
    Debug.Log(progress);
    }
    else
    {
    progress = 0;
    }

    if (timeRemaining > 0)
    {
    timeRemaining -= Time.deltaTime;
    DisplayTime(timeRemaining);
    }
    else
    {
    Debug.Log("Time has run out!");
    timeRemaining = 5;
    timerIsRunning = false;


    }
    }
    }
    void DisplayTime(float timeToDisplay)
    {
    timeToDisplay += 1;
    float minutes = Mathf.FloorToInt(timeToDisplay / 60);
    float seconds = Mathf.FloorToInt(timeToDisplay % 60);
    timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
    }
    -------

    Everything works great except I don't have it running at the start of the game, I want it to run at the press of a button and reset itself once completed, but I can't seem to even get it to run on the button press.


    upload_2022-7-1_21-27-57.png
    This is the button which is imported from unity itself in the UI section. I tried to make the "On Click()" link to the "timerIsRunning" bool in the script ( to set it to true to make the script run ) which I could only have assumed was the Timer.enabled option since nothing else made sense.
    upload_2022-7-1_21-35-43.png
    But obviously this hasn't work and I've hit a dead end, any ideas or extra information needed?
    (Please try to explain the simplest way you can, thanks!)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,674