Unity:仅在单击按钮后才能开始更新(Unity和编码中的新手)

时间:2018-12-03 16:33:24

标签: c# unity3d unityscript

我已经使用Update()设置了倒数计时器,但是当我统一运行时,倒计时会自动开始,我希望仅在单击按钮后才能开始倒计时。当我取消按钮功能后,它似乎可以正常工作,但是再次需要按钮,这样定时器就不会自动启动...不胜感激!

(完整代码...如果有帮助的话)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CountdownTimer : MonoBehaviour
{
[SerializeField] Text countdownText;
public AudioSource audioData;
public Button m_timer1;

private bool timerOn;

float minutes = 0;
float seconds = 3;
float miliseconds = 0;

void Start()
{
    audioData = GetComponent<AudioSource>();

    timerOn = false;

    Button btn = m_timer1.GetComponent<Button>();
    btn.onClick.AddListener(ClickBtn);

}

public void ClickBtn()
{
    //Debug.Log("doesthiswork???!!");
    timerOn = true;
    Invoke(Update);
}

public void Update()
{
    if (timerOn == true)
    {
        Debug.Log("Yo");
        if (minutes <= 0 && seconds <= 0 && miliseconds <= 0)// timerOn = false
        {
            timerOn = false;
            //Debug.Log("CurrentTime = 0");
            Music_Play();

        }

        else if (miliseconds <= 0)
        {
            Debug.Log("ithasreachedthisstage");
            if (seconds <= 0)
            {
                minutes--;
                seconds = 59;
            }

            else if (seconds >= 0)
            {
                seconds--;
            }

            miliseconds = 100;
        }

        miliseconds -= Time.deltaTime * 100;

        countdownText.text = string.Format("{0}:{1}", minutes, seconds); //countdown
    }

}

void Music_Play() //this works, now make the button work!!!
{
    audioData.Play();
    //Debug.Log("musicon");
}

}

1 个答案:

答案 0 :(得分:1)

更新仅在component.enabled == true时运行; 如果取消选中组件名称旁边的复选框,它将在启用它之前开始更新。您可以轻松地将此按钮附加到UI enter image description here按钮