一行代码实现生成怪物(一个集合委托、泛型、结构体的协程自定义工具)
今天给大家分享一个小工具,平时大家是不是有这么一个需求(举个例子):在达到某个条件下隔5秒开始生成怪物,然后怪物每隔1秒生成一个,一共生成100个.大家肯定想到这玩意和计时器有关,但是由于计时器的帧率可能会误差0.02秒,所以个人还是不推荐啦,于是想到了携程,想了一下,这里一个携程那里一个协程,非常冗余,代码不美观,何尝我们不做一个协程管理器呢~
-
建立一个类,叫做TaskManger,这个类是用来管理协程的
-
我们定义委托,用来承载需要执行的函数.因为协程只能有一个参数,所以我们用结构体把数据打包起来.我们需要给多种类型的参数,所以我们定义泛型的委托.好的,其中的道理大家自己好好理解吧~
TaskManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 无返回值无参数的委托
/// </summary>
public delegate void NoRetNoPraFunc();
/// <summary>
/// 存储数据的结构体
/// </summary>
public struct NoRetNoPraData
{
public float time;
public NoRetNoPraFunc func;
public NoRetNoPraData(float mTime, NoRetNoPraFunc mFunc)
{
time = mTime;
func = mFunc;
}
}
/// <summary>
/// 一个泛型类型的委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="T_parameter"></param>
public delegate void NoRetPraFunc<T>(T T_parameter);
/// <summary>
/// 存储数据的泛型结构体
/// </summary>
/// <typeparam name="T"></typeparam>
public struct NoRetPraData<T>
{
public float interval;
public int count;
public T T_param;
public float time;
public NoRetPraFunc<T> func;
public NoRetPraData(NoRetPraFunc<T> mFunc, float mTime,T mPara,int mCount,float mInterval)
{
func = mFunc;
time = mTime;
T_param = mPara;
count = mCount;
interval = mInterval;
}
}
public class TaskManager : MonoBehaviour {
public static TaskManager _instance;
public TaskManager() {
_instance = this;
}
IEnumerator Doing(NoRetNoPraData mStructData)
{
yield return new WaitForSeconds(mStructData.time);
mStructData.func();
}
IEnumerator Doing<T>(NoRetPraData<T> mStructData) {
yield return new WaitForSeconds(mStructData.time);
for (int i = 0;i<mStructData.count;i++) {
yield return new WaitForSeconds(mStructData.interval);
mStructData.func(mStructData.T_param);
}
}
public void DoingInSeconds(NoRetNoPraFunc func, float time)
{
NoRetNoPraData mData = new NoRetNoPraData(time, func);
StartCoroutine("Doing", mData);
}
/// <summary>
/// 开启携程
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="func">委托</param>
/// <param name="time">等待执行时间</param>
/// <param name="mParameter">泛型参数</param>
/// <param name="mCount">循环的次数</param>
/// <param name="mInterval">循环的时间间隔</param>
public void DoingInSeconds<T>(NoRetPraFunc<T> func ,float time ,T mParameter,int mCount,float mInterval) {
NoRetPraData<T> mData = new NoRetPraData<T>(func, time, mParameter, mCount, mInterval);
StartCoroutine(Doing<T>(mData));
}
}
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
TaskManager._instance.DoingInSeconds(()=> {
print("3.0f");
},2.0f);
TaskManager._instance.DoingInSeconds<string>((string s)=> {
print(s);
},5.0f,"我的女神在隔壁",8,0.1f);
}
}
网友评论