Unity中定时执行事件的定时器

来源:互联网 发布:qq飞车白银雷诺数据 编辑:程序博客网 时间:2024/06/06 23:59

       Unity开发一年多了,菜鸟一个,最近半年项目做得紧,一直想写写博客记录下项目中遇见的困难和最后解决办法,可是由于各种原因没有启动,今天终于开始启动了!!!

       一直从事VR开发,项目中经常需要用到定时执行某一事件的功能,因此写了一个简易定时器,勉强够用。下面直接上代码:

       下面这个脚本主要作用是创建一个空对象(从创建出来到游戏结束时),用来挂载各种需要常载脚本。

using UnityEngine;public class DontDestroyGO<T> : MonoBehaviour where T: MonoBehaviour{    protected static GameObject dontDestroyGO;    //创建挂载定时器脚本的游戏对象    internal static void CreateDontDestroyGO()    {        if (dontDestroyGO == null)        {            dontDestroyGO = new GameObject("DontDestroyGO");            DontDestroyOnLoad(dontDestroyGO);            #if (UNITY_EDITOR && !DEBUG)        dontDestroyGO.hideFlags = HideFlags.HideInHierarchy;  #endif} if (!dontDestroyGO.GetComponent<T>()) ontDestroyGO.AddComponent<T>(); }}


接下来上定时器的脚本


using UnityEngine;using System.Collections.Generic;using System;namespace HMLTools{    /// <summary>    /// 定时任务控制    /// </summary>    public class TimerEvent : DontDestroyGO<TimerEvent>    {        static List<float> timer_Timer = new List<float>();//记录用户传入的定时时间        static List<float> timer_Time = new List<float>();//定时器,对应每个事件        static List<Action> eventList = new List<Action>();//存储添加的定时事件        static List<bool> isRepeat = new List<bool>();//存储每个事件的条件(是否重复)        void FixedUpdate()        {            if (timer_Time.Count < 1) return;            for (int i = 0; i < timer_Time.Count; i++)            {                timer_Time[i] -= Time.fixedDeltaTime;//开始计时                if (timer_Time[i] <= 0)                {                    eventList[i]();//计时完毕后执行事件                    if (isRepeat[i])                        timer_Time[i] = timer_Timer[i];//如果此事件为重复执行的事件,则重置计时时间                    else                    {                        //如果为单次执行事件,执行完则移除该事件及该事件的其他信息                        timer_Timer.RemoveAt(i);                        timer_Time.RemoveAt(i);                        eventList.RemoveAt(i);                        isRepeat.RemoveAt(i);                    }                }            }        }        /// <summary>        /// 添加固定更新定时事件        /// </summary>        /// <param name="time">定时时长</param>        /// <param name="callback">回调事件</param>        /// <param name="isrepeat">是否重复(不传入,则默认为不重复执行)</param>        public static void Add(float time, Action callback, bool isrepeat = false)        {            CreateDontDestroyGO();//添加事件时,如果没有常存对象,则创建一个;有的话则跳过                       timer_Timer.Add(time);            timer_Time.Add(time);            eventList.Add(callback);            isRepeat.Add(isrepeat);        }    }}

代码没什么难度很容易理解,在此希望各位大神留下宝贵的意见,我好改进,谢谢!


原创粉丝点击