栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity 计时器工具类

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity 计时器工具类

一个项目中可能要使用多个计时器,为了应对这种情况,写了一个计时器管理器

单例

public class Singleton where T : new()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }
}

计时器类

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

public class Timer
{
    string name;
    public Timer(string name)
    {
        this.name = name;
    }

    bool isRecording = false;
    float startTime;

    public void StartRecording()
    {
        isRecording = true;
        startTime = Time.time;
    }

    public float GetCurrentRecord()
    {
        if (isRecording)
        {
            float deltaTime = Time.time - startTime;
            return deltaTime;
        }
        else return 0;
    }

    public void Reset()
    {
        isRecording = false;
        startTime = 0;
    }
}

计时器管理器类

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

public class TimerManager : Singleton
{
    Dictionary dict = new Dictionary();

    void CreateTimer(string timerName)
    {
        Timer timer = new Timer(timerName);
        dict.Add(timerName, timer);
    }

    public Timer GetTimer(string timerName)
    {
        if (!dict.ContainsKey(timerName))
            CreateTimer(timerName);
        return dict[timerName];
    }
}

使用方法

Timer timer;
void Awake()
{
    timer = TimerManager.Instance.GetTimer("Arrow");
}

timer.StartRecording();
timer.GetCurrentRecord();
timer.Reset();

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号