网页资讯视频图片知道文库贴吧地图采购
进入贴吧全吧搜索

 
 
 
日一二三四五六
       
       
       
       
       
       

签到排名:今日本吧第个签到,

本吧因你更精彩,明天继续来努力!

本吧签到人数:0

一键签到
成为超级会员,使用一键签到
一键签到
本月漏签0次!
0
成为超级会员,赠送8张补签卡
如何使用?
点击日历上漏签日期,即可进行补签。
连续签到:天  累计签到:天
0
超级会员单次开通12个月以上,赠送连续签到卡3张
使用连续签到卡
01月10日漏签0天
游戏编程吧 关注:15,932贴子:46,634
  • 看贴

  • 图片

  • 吧主推荐

  • 游戏

  • 0回复贴,共1页
<<返回游戏编程吧
>0< 加载中...

Unity3d时间、计时管理器简介

  • 只看楼主
  • 收藏

  • 回复
  • 你就是最吊的
  • 6级大佬
    6
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

在之前文章我们提到过定时器的做法《unity教程-自定义Clock定时器类 》,在平时的游戏开发过程中,我们或多或少的会用到时间类,比如技能的冷却时间,角色的生命回复等等都会用到,而处理方式也有很多种,我们可以在每个技能上面挂载一个时间类,也可以提供一个时间管理器,来统一管理技能的冷却,个人推荐第二种做法,因为这样会更加精准!
时间管理器的类主要包括 TimerManager.cs,代码如下:
using Unity Engine;
using System;
using System.Collections.Generic;
///
/// 移动管理
///
public class TimerManager
{
public static float time;
public static Dictionary timerList = new Dictionary();
public static void Run()
{
// 设置时间值
TimerManager.time = Time.time;
TimerItem[] objectList = new TimerItem[timerList.Values.Count];
timerList.Values.CopyTo(objectList, 0);
// 锁定
foreach(TimerItem timerItem in objectList)
{
if(timerItem != null) timerItem.Run(TimerManager.time);
}
}
public static void Register(object objectItem, float delayTime, Action callback)
{
if(!timerList.ContainsKey(objectItem))
{
TimerItem timerItem = new TimerItem(TimerManager.time, delayTime, callback);
timerList.Add(objectItem, timerItem);
}
}
public static void UnRegister(object objectItem)
{
if(timerList.ContainsKey(objectItem))
{
timerList.Remove(objectItem);
}
}
}
TimerItem.cs,代码如下:
using UnityEngine;
using System;
public class TimerItem
{
///
/// 当前时间
///
public float currentTime;
///
/// 延迟时间
///
public float delayTime;
///
/// 回调函数
///
public Action callback;
public TimerItem(float time, float delayTime, Action callback)
{
this.currentTime = time;
this.delayTime = delayTime;
this.callback = callback;
}
public void Run(float time)
{
// 计算差值
float offsetTime = time - this.currentTime;
// 如果差值大等于延迟时间
if(offsetTime >= this.delayTime)
{
float count = offsetTime / this.delayTime - 1;
float mod = offsetTime % this.delayTime;
for(int index = 0; index < count; index ++)
{
this.callback();
}
this.currentTime = time - mod;
}
}
}
测试用例代码如下:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Demo : MonoBehaviour
{
public GameObject roleObject;
void Awake()
{
TimerManager.Register(this, 0.3f, ()=>
{
Debug.Log("0.3 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff"));
});
TimerManager.Register(this.gameObject, 1f, ()=>
{
Debug.Log("1 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff"));
});
}
void Update()
{
TimerManager.Run ();
}
}
好了,本篇unity3d教程到此结束,下篇我们再会!
资源地址: http://cg.silucg.com/dongman/unity3d/7981.html (分享请保留)


登录百度账号

扫二维码下载贴吧客户端

下载贴吧APP
看高清直播、视频!
  • 贴吧页面意见反馈
  • 违规贴吧举报反馈通道
  • 贴吧违规信息处理公示
  • 0回复贴,共1页
<<返回游戏编程吧
分享到:
©2026 Baidu贴吧协议|隐私政策|吧主制度|意见反馈|网络谣言警示