Unity 计时器 定时器

在网上找了一些资料,自己修改了,实现比较简单,要求精度不是很高的用这个没有问题

效果如下:

代码如下:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class Timer
{
    #region Public Parameters
    /// <summary>
    /// 开始时间
    /// </summary>
    public float StartTime { get; private set; }
    /// <summary>
    /// 延迟时间(开始后的多少秒执行)
    /// </summary>
    public float DelayTime { get; private set; }
    /// <summary>
    /// 持续时间
    /// </summary>
    public float Duration { get; private set; }
    /// <summary>
    /// 结束的时间点
    /// </summary>
    public float EndTime { get; private set; }
    /// <summary>
    /// 当前计时器运行的总时间点
    /// </summary>
    public float CurTime { get; private set; }

    /// <summary>
    /// 运行标识
    /// </summary>
    public bool IsStart { get; private set; }
    /// <summary>
    /// 运行标识
    /// </summary>
    public bool IsPause { get; private set; }

    //开始和结束等事件
    public event Action OnStart;
    public event Action OnEnd;
    public event Action OnUpdate;
    public event Action OnCancel;
    public event Action OnPause;
    public event Action OnContinue;

    //Add
    public event Action OnUpdateCustom;
    public float UpdateCustomTime = 1.0f;
    public float TempUpdateCustomTime = 0.0f;

    /// <summary>
    /// 开始次数
    /// </summary>
    public int StartCount { get; private set; }
    /// <summary>
    /// 完成次数
    /// </summary>
    public int FinishCount { get; private set; }

    private float originalDelayTime;
    private float originalDurationTime;
    #endregion
    /// <summary>
    /// 构造函数,设置计时器
    /// </summary>
    /// <param name="duration">需要执行多少时间</param>
    public Timer(float duration)
    {
        Duration = duration;
        originalDelayTime = 0;
        originalDurationTime = duration;
        DelayTime = 0;
    }
    /// <summary>
    /// 构造函数,设置计时器
    /// </summary>
    /// <param name="delaytime">延迟多少秒后执行</param>
    /// <param name="duration">需要执行的时间</param>
    public Timer(float delaytime, float duration)
    {
        Duration = duration;
        originalDelayTime = delaytime;
        originalDurationTime = duration;
        DelayTime = delaytime;
    }

    /// <summary>
    /// 百分比
    /// </summary>
    public float Ratio
    {
        get
        {
            if (!IsStart)
            {
                return 0;
            }
            else
            {
                return (EndTime - CurTime) / Duration;
            }
        }
    }


    //开始计时 Timer类不继承于MonoBehavior,该方法不会在任何对象开始时被调用。
    public void Start()
    {
        IsStart = true;
        IsPause = false;

        StartTime = Time.time;
        CurTime = StartTime;
        EndTime = StartTime + Duration;
        TempUpdateCustomTime = UpdateCustomTime;
        ++StartCount;
        TimerUpdate.RemoveTimer(this);
        TimerUpdate.AddTimer(this);
        if (OnStart != null) OnStart();
    }

    //更新时间,并检查状态。
    public void Update()
    {
        CurTime += Time.deltaTime;

        if (IsPause)
        {
            EndTime += Time.deltaTime;
        }

        if (DelayTime > 0 && !IsPause)
        {
            DelayTime -= Time.deltaTime;
            EndTime += Time.deltaTime;
            Debug.Log("执行延迟");
        }
        else if (CurTime > EndTime)
        {
            End();
        }
        else if (OnUpdate != null && !IsPause)
        {
            OnUpdate();
        }
        else if (OnUpdateCustom != null && !IsPause)//Add
        {
            TempUpdateCustomTime -= Time.fixedDeltaTime;
            if (TempUpdateCustomTime <= 0)
            {
                if (OnUpdateCustom != null) OnUpdateCustom();
                TempUpdateCustomTime = UpdateCustomTime;
            }
        }

    }

    //计时器结束
    public void End()
    {
        IsStart = true;
        FinishCount++;
        if (OnEnd != null) OnEnd();
        TimerUpdate.RemoveTimer(this);
    }

    //取消接口
    public void Cancel()
    {
        IsStart = false;
        if (OnCancel != null) OnCancel();
        TimerUpdate.RemoveTimer(this);
        DelayTime = originalDelayTime;
        Duration = originalDurationTime;
    }
    //暂停接口
    public void Pause()
    {
        IsPause = true;
        if (OnPause != null) OnPause();
    }

    //继续接口
    public void Continue()
    {
        IsPause = false;
        if (OnContinue != null) OnContinue();
    }

    //重置清零接口
    public void Reset()
    {
        IsStart = false;
        IsPause = false;

        TimerUpdate.RemoveTimer(this);
    }
    /// <summary>
    /// 重新开始
    /// </summary>
    public void Restart()
    {
        DelayTime = originalDelayTime;
        Duration = originalDurationTime;
        Start();
    }
}


public class TimerUpdate : MonoBehaviour
{
    static List<Timer> timers = new List<Timer>();

    //添加计时器
    public static void AddTimer(Timer timer)
    {

        if (!timers.Contains(timer))
        {
            timers.Add(timer);
        }
        else
        {
            Debug.LogWarning("已经添加此计时器,请勿重复添加");
        }
    }

    //移除计时器
    public static void RemoveTimer(Timer timer)
    {
        if (timers.Contains(timer))
        {
            timers.Remove(timer);
        }
    }

    //每帧更新
    void FixedUpdate()
    {
        for (int i = 0; i < timers.Count; i++)
        {
            timers[i].Update();
        }

    }

}

逻辑Code:

using UnityEngine;
using System.Collections;

public class TestCube : MonoBehaviour {

    Timer time1;

    void Start ()
    {
        time1 = new Timer(0,10);
        time1.OnUpdate += SetScale;
    }

    void SetScale()
    {
        transform.localScale = new Vector3(time1.Ratio, time1.Ratio, time1.Ratio);
    }

    public void StartBtn()
    {
        time1.Start();
    }
    public void PauseBtn()
    {
        time1.Pause();
    }
    public void ContinueBtn()
    {
        time1.Continue();
    }
    public void CancelBtn()
    {
        time1.Cancel();
    }
    public void ResetBtn()
    {
        time1.Reset();
    }
    public void RestartBtn()
    {
        time1.Restart();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,351评论 25 709
  • 生活中有时感觉心烦 心烦时最好的选择 不用管天气如何 信步出去走走 走在林荫中的小路上 透着斑驳陆离的树叶缝隙 看...
    苏吉儿阅读 142评论 0 2
  • 《如何打造你的独特观点》作业 作业1:和出租车司机的沟通 A:师傅,你们一天要工作几个小时?工作时间这么长,肯定比...
    Videalous阅读 183评论 0 0
  • 首先手仗式做好,慢慢弯曲左膝,将左脚抵于右腿膝盖外侧,此时右腿可以保持不变,也可以弯曲膝盖来到左侧臀部旁边。 吸气...
    随笔s阅读 601评论 0 0
  • 我是一个非常、非常、非常普通的企业员工,当取得了许多小小、小小、小小的成就时,就会非常、非常、非常地激动。所以你看...
    新生大学阅读 426评论 0 1