Unity UGUI makes a simple skill cooldown CD

In fact, it is very simple to use UGUI to make skill CD

First use the UGUI that comes with unity to build the UI interface as shown below:


The specific code is as follows:

First you need to reference the namespace using UnityEngine.UI;

The following definitions are all public, just drag them

Don't forget to bind events to buttons


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

public class Test : MonoBehaviour {
    public float timeCount;//Timer
    public float timeCD;//Skill CD
    public Image image;//Mask image
    public Text text;//Timing text
    public Button btn;//Define the skill button
    public bool isCooling;//Whether it is a cooling state
	// Use this for initialization
	void Start () {
		
	}
	public void BtnEvent()
    {
        if (!isCooling)
        {
            image.fillAmount = 1;//Press button mask image fillAmount=1;
            image.gameObject.SetActive(true);//Display mask image
            text.gameObject.SetActive(true);//Display the digital text box
            text.text = timeCD.ToString("f1");//The number displayed in the text box and keep one decimal place
            isCooling = true;
            timeCount = timeCD;
        }

    }
	// Update is called once per frame
	void Update () {
        if (isCooling)
        {
            timeCount -= Time.deltaTime;//Timer assignment
            image.fillAmount = timeCount / timeCD;//The fillAmount assignment of the mask image
            text.text = timeCount.ToString("f1");//Assign the text box to one decimal place
            if (timeCount<=0)
            {
                isCooling = false;
                image.gameObject.SetActive(false);
                text.gameObject.SetActive(false);

            }

        }
	}
}
If there are any shortcomings, please point them out!!!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325565669&siteId=291194637