TimeControl.cs 2.14 KB
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class TimeControl : Singleton<TimeControl>
{
    /// <summary>
    /// 目标时间
    /// </summary>
    private float _totalTime;

    /// <summary>
    /// 当前时间
    /// </summary>
    private float _curTime;

    /// <summary>
    /// 回调
    /// </summary>
    private UnityAction _timeCallBack;

    /// <summary>
    /// 是否开始计时
    /// </summary>
    private bool _isStart = false;

    /// <summary>
    ///  是否时单词计时(计时器只执行一次  或者  按设置的间隔时间执行)
    /// </summary>
    private bool _isOnce;

    void Start()
    {
    }

    void Update()
    {
        if (_isStart)
        {
            _curTime += Time.deltaTime;
            if (_curTime >= _totalTime)
            {
                _curTime = 0;
                // 如果是单次计时器  此时结束计时器
                if (_isOnce)
                {
                    _isStart = false;
                }
                if (_timeCallBack != null)
                {
                    _timeCallBack.Invoke();
                }
            }
        }
    }


    /// <summary>
    /// 按照指定的时间间隔重复执行回调函数。
    /// </summary>
    /// <param name="interval"></param>
    /// <param name="action"></param>
    public void Schedule(float interval, UnityAction action)
    {
        _totalTime = interval;
        _timeCallBack = action;
        _isStart = true;
        _isOnce = false;
    }


    /// <summary>
    /// 延迟执行回调函数,且只会执行一次。
    /// </summary>
    /// <param name="interval"></param>
    /// <param name="action"></param>
    public void ScheduleOnce(float interval, UnityAction action)
    {
        _totalTime = interval;
        _timeCallBack = action;
        _isStart = true;
        _isOnce = true;
    }


    /// <summary>
    /// 结束所有的计时器
    /// </summary>
    public void UnSchedule()
    {
        _isStart = false;
        _curTime = 0f;
        _totalTime = 0f;
        _timeCallBack = null;
    }
}