|
在之前文章我们提到过定时器的做法《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 (分享请保留)
|
|