Unity中的计时器

用途

通过TimeSys生成1个Timer。
生成时,可设置是否立即开始计时、该计时器是否忽略Time.timeScale变化的影响

对于单个计时器,可以:开始计时、暂停计时、继续计时、重置时间。

UnityTime相关的小知识

  1. FixedUpdate()的执行频率会受Time.timeScale的影响,当scale=0时不执行。
  2. Update和LateUpdate不受Time.timeScale的影响。
  3. Time.deltaTime受Time.timeScale的影响,Time.unscaledDeltaTime不受Time.timeScale的影响。

具体代码

TimerSys和Timer

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

public class TimerSys
{
    private static TimerSys _instance;
    public static TimerSys Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new TimerSys();
            }
            return _instance;
        }
    }
    private List<Timer> _timerList;

    public TimerSys()
    {
        _timerList = new List<Timer>();
        MonoSys.Instance.AddUpdateEvent(OnUpdateEvent);
    }

    public void Destroy()
    {
        MonoSys.Instance?.RemoveUpdateEvent(OnUpdateEvent);
        Clear();
        _timerList = null;
    }

    public void Clear()
    {
        if (_timerList == null)
        {
            return;
        }
        
        foreach (var timer in _timerList)
        {
            timer.Destroy();
        }
        _timerList.Clear();
    }

    public Timer CreateTimer(bool shouldImmediateStart = true,  bool shouldIgnoreTimeScale = false)
    {
        Timer timer = new Timer(shouldImmediateStart, shouldIgnoreTimeScale);
        _timerList.Add(timer);
        return timer;
    }

    public bool DestroyTimer(Timer timer)
    {
        bool destroySuccessfully = false;
        if (_timerList.Contains(timer))
        {
            timer.Destroy();
            _timerList.Remove(timer);
            destroySuccessfully = true;
        }
        return destroySuccessfully;
    }

    private void OnUpdateEvent()
    {
        if (_timerList != null && _timerList.Count > 0)
        {
            for (int i = 0; i < _timerList.Count; i++)
            {
                if (_timerList[i] != null)
                {
                    _timerList[i].UpdateTime();
                }
            }
        }
    }
}

public class Timer
{
    private float _time;
    public float Time
    {
        get { return _time; }
    }

    private readonly bool ShouldIgnoreTimeScale;
    public bool IsPaused{ get; private set; }


    public event Action<float> TimeChangedEvent;
    public event Action PauseEvent;
    public event Action ContinueEvent;

    public Timer(bool shouldImmediateStart, bool shouldIgnoreTimeScale)
    {
        ShouldIgnoreTimeScale = shouldIgnoreTimeScale;
        if (shouldImmediateStart)
        {
            BeginTime();
        }
        else
        {
            Pause();
        }
    }

    public void Destroy()
    {

    }

    // 修改时间
    public void UpdateTime()
    {
        if (!IsPaused)
        {
            if (ShouldIgnoreTimeScale)
            {
                ChangeTime(_time + UnityEngine.Time.unscaledDeltaTime);
            }
            else
            {
                ChangeTime(_time + UnityEngine.Time.deltaTime);
            }
        }
    }

    private void ChangeTime(float time)
    {
        _time = time;
        TimeChangedEvent?.Invoke(_time);
    }

    // 开始计时
    public void BeginTime()
    {
        Reset();
        Continue();
    }
    // 停止计时
    public void Pause()
    {
        IsPaused = true;
        PauseEvent?.Invoke();
    }
    // 继续计时
    public void Continue()
    {
        IsPaused = false;
        ContinueEvent?.Invoke();
    }
    // 重置时间
    public void Reset()
    {
        ChangeTime(0f);
    }

    // 格式化显示
    public static string FormatStr(float time)
    {
        int intTime = (int)time;
        int hour = intTime / 3600;
        int minute = (intTime - 3600 * hour) / 60;
        int second = intTime - 3600 * hour - 60 * minute;

        string hourStr = hour.ToString().PadLeft(2, '0');
        string minuteStr = minute.ToString().PadLeft(2, '0');
        string secondStr = second.ToString().PadLeft(2, '0');
        string timeStr = string.Format("{0}:{1}:{2}", hourStr, minuteStr, secondStr);
        return timeStr;
    }
}

MonoSys
用途:让不继承MonoBehaviour能使用MonoBehaviour提供的一些方法。(通过注册事件的方式)

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

public class MonoController : MonoBehaviour
{
    public event Action ApplicationPauseEvent;
    public event Action ApplicationQuitEvent;
    public event Action UpdateEvent;

    private void OnApplicationPause(bool pauseStatus)
    {
        if (pauseStatus)
        {
            ApplicationPauseEvent?.Invoke();
        }
    }
    private void OnApplicationQuit()
    {
        ApplicationQuitEvent?.Invoke();
    }

    private void Update()
    {
        UpdateEvent?.Invoke();
    }
}
public class MonoSys
{
    private static MonoSys _instance;
    public static MonoSys Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MonoSys();
            }

            return _instance;
        }
    }
    private MonoController _monoController;
    private MonoSys()
    {
        var parentGo = GameObject.Find("Singleton");
        if (parentGo == null)
        {
            parentGo = new GameObject("Singleton");
            UnityEngine.Object.DontDestroyOnLoad(parentGo);
        }

        GameObject go = new GameObject(nameof(MonoController));
        go.transform.SetParent(parentGo.transform);
        _monoController = go.AddComponent<MonoController>();
    }

    public Coroutine StartCoroutine(IEnumerator routine)
    {
        return _monoController.StartCoroutine(routine);
    }

    public void StopCoroutine(IEnumerator routine)
    {
        _monoController.StopCoroutine(routine);
    }

    public void AddApplicationQuitEvent(Action action)
    {
        _monoController.ApplicationQuitEvent += action;
    }

    public void RemoveApplicationQuitEvent(Action action)
    {
        _monoController.ApplicationQuitEvent -= action;
    }

    public void AddApplicationPauseEvent(Action action)
    {
        _monoController.ApplicationPauseEvent += action;
    }

    public void RemoveApplicationPauseEvent(Action action)
    {
        _monoController.ApplicationPauseEvent -= action;
    }

    public void AddUpdateEvent(Action action)
    {
        _monoController.UpdateEvent += action;
    }

    public void RemoveUpdateEvent(Action action)
    {
        _monoController.UpdateEvent -= action;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ![Flask](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW...
    极客学院Wiki阅读 8,147评论 0赞 3
  • 不知不觉易趣客已经在路上走了快一年了,感觉也该让更多朋友认识知道易趣客,所以就谢了这篇简介,已做创业记事。 易趣客...
    Physher阅读 4,108评论 1赞 2
  • 双胎妊娠有家族遗传倾向,随母系遗传。有研究表明,如果孕妇本人是双胎之一,她生双胎的机率为1/58;若孕妇的父亲或母...
    邺水芙蓉hibiscus阅读 4,149评论 0赞 2
  • 今天理好了行李,看到快要九点了,就很匆忙的洗头洗澡,(心存一份念想,你总会打给我的🐶)然后把洗头液当成沐浴液了😨,...
    bevil阅读 3,042评论 1赞 1
  • 那年我们15,像阳光一样温暖的年纪。每天我都会骑自行车上学,路过田野,工厂,医院,村庄,有微风,有阳光,有绿...
    木偶说爱你阅读 2,629评论 0赞 3

友情链接更多精彩内容