单击按钮文字延迟消失_Timer的简单实用

126 阅读1分钟

文字逐渐消失

效果演示:
效果演示,在B站上,视频长达11秒。
b站链接。

/*
名称:文字逐渐消失
功能:当点击按钮之后文字出现,延迟一定时间之后文字逐渐消失
*/
using System.Collections;
using System.Collections.Generic;
using System.Timers;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    public Button buttonA;
    public Text _text;
    private bool isbeclikck = false;
    private Color colorOrgion = new Color(0, 0, 0, 1);//默认为黑色
    private float Alpha = 1.0f;
    Timer timer = new Timer(2000);//延迟2秒

    void Start()
    {
        buttonA.onClick.AddListener(Black);
        _text.color = new Color(0, 0, 0, 0);//默认不显示
        
        timer.Elapsed += (object sender, ElapsedEventArgs e) =>
        {
            isbeclikck = true;
        };//这里使用了拉姆达表达式,可以使用    timer.Elapsed +=Timer_Elapsed;     代替


        timer.AutoReset = false; //如果 System.Timers.Timer 应在每次间隔结束时引发 System.Timers.Timer.Elapsed 事件,则为 true;如果它仅在间隔第一次结束后引发一次,可以新建一颗控制台应用,然后F12跟进去查看详情,这是我复制粘贴的,
        timer.Enabled = true;// 如果 System.Timers.Timer 应引发 System.Timers.Timer.Elapsed 事件,则为 true;否则,为 false。
    }

    private void Update()
    {
        if (isbeclikck)
        {
            Alpha = Alpha - (Time.deltaTime);//通过修改阿尔法值来设置显示或隐藏
            colorOrgion.a = Alpha;
            _text.color = colorOrgion;
        }
        if (colorOrgion.a <= 0)//如果阿尔法小于0就代表文字完全消失了
        {
            isbeclikck = false;
        }
    }

    public void Black()
    {
        _text.color = new Color(0, 0, 0, 1);//只要点击按钮就会把文字的阿尔法值设置为1
        Alpha = 1;
        colorOrgion.a = 1.0f;
        timer.Start();//开始计时,2秒之后执行Timer_Elapsed方法;
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        isbeclikck = true;
    }
}

框架搭建 上图是框架搭建,创建空物体然后将脚本拖拽到gameObject上,然后创建一个text,和button,将button和text拖拽到gameObject脚本上对应的位置,即可运行查看效果。
如有不懂随时私信。

over.