本文共 4237 字,大约阅读时间需要 14 分钟。
////// 帧定时任务/// public class FrameTask{ public int taskID;//任务id public int count;//循环次数 public int frameTime;//目标时间 public int delayTime;//延迟时间 public Action callBack; //执行的方法 public FrameTask(int taskID, int count,int frameTime, int delayTime, Action callBack) { this.taskID = taskID; this.count = count; this.frameTime = frameTime; this.delayTime = delayTime; this.callBack = callBack; }
#region 帧任务 private int frame = 0; //执行帧任务 private void ExecuteFrameTask() { //从缓存里里面取出来 if (cacheFrameTasks.Count > 0) { foreach (FrameTask task in cacheFrameTasks) { frameTasks.Add(task); } } cacheFrameTasks.Clear(); frame += 1; for (int i = 0; i < frameTasks.Count; i++) { FrameTask frameTask = frameTasks[i]; if (frame < frameTask.frameTime) { continue; } else { if (frameTask.callBack != null) { frameTask.callBack.Invoke(); } //到达时间了 //判断任务执行的次数 if (frameTask.count == 1) { //移除任务 frameTasks.RemoveAt(i); i--; cacheIdList.Add(frameTask.taskID); break; } else { if (frameTask.count != 0) { frameTask.count -= 1; } //时间加 frameTask.frameTime += frameTask.delayTime; } } } } //添加任务 默认是毫秒 返回添加任务的id public int AddFrameTask(int frameTime, int delayTime, Action callBack, int count=1) { int taskID = GettaskId(); FrameTask timeTask = new FrameTask(taskID, count, frameTime+frame, delayTime, callBack); //添加到idList里 //添加到缓存里 idList.Add(taskID); cacheFrameTasks.Add(timeTask); return taskID; } //删除任务 public bool DeleteFrameTask(int taskId) { //寻找任务 bool isDelete = false; for (int i = 0; i < cacheFrameTasks.Count; i++) { if (cacheFrameTasks[i].taskID == taskId) { cacheFrameTasks.RemoveAt(i); isDelete = true; break; } } if (!isDelete) { for (int i = 0; i < frameTasks.Count; i++) { if (frameTasks[i].taskID == taskId) { frameTasks.RemoveAt(i); isDelete = true; break; } } } return isDelete; } //替换任务 public bool ReplaceFrameTask(int id, int frameTime, int delayTime, Action callBack, int count= 1) { //构造新任务 int taskID = GettaskId(); FrameTask newFrameTask = new FrameTask(taskID, count, frameTime+frame, delayTime, callBack); //寻找要替换的id //寻找任务 bool isReplace = false; for (int i = 0; i < cacheFrameTasks.Count; i++) { if (cacheFrameTasks[i].taskID == id) { cacheFrameTasks[i] = newFrameTask; isReplace = true; break; } } if (!isReplace) { for (int i = 0; i < frameTasks.Count; i++) { if (frameTasks[i].taskID == id) { frameTasks[i] =newFrameTask; isReplace = true; break; } } } return isReplace; } #endregion
public void AddFrameTask() { taskFrameID=timeSys.AddFrameTask(60, 60, () => { Debug.Log("执行帧任务:" + taskFrameID); }, 6); } public void DeleteFrameTask() { bool success = timeSys.DeleteFrameTask(taskFrameID); Debug.Log("删除帧任务id:" + taskID + success); } public void ReplaceFrameTask() { bool success = timeSys.ReplaceFrameTask(taskFrameID,60, 60, () => { Debug.Log("执行新的替换的帧任务"); }, 5); Debug.Log("替换:" + success); }
转载地址:http://pjrxo.baihongyu.com/