版权声明:转载注明出处 https://blog.csdn.net/qq_19428987/article/details/87802129
设计Scheduler最主要的目的是在Unity中实现定时器的功能,因此我重点记录下定时器的设计,其他的作为参考。
定时器中需要包含:定时时间、出发的任务、重复次数等,根据这些来定义Timer基类(源码):
/// <summary>
/// 定时器对象,记录定时时间,触发事件
/// </summary>
public class Timer
{
/// <summary>
/// 记录原始数据
/// </summary>
private float delay;
/// <summary>
/// 默认定时器只触发一次,repetTimes=1;
/// repetTimes>1:指定重复次数
/// repetTimes=-1:无限次重复
/// </summary>
private short repetTimes;
/// <summary>
/// 真实数据计算剩余时间
/// </summary>
private float residueTime;
/// <summary>
/// 剩余重复次数
/// </summary>
private short residueTimes;
private bool unScale;
private System.Action task;
private float unscaledDeltaTime;
private float deltaTime;
public ushort ID;
public Timer(float _delay, short _repetTimes, bool _unScale, System.Action _task)
{
this.delay = _delay;
this.repetTimes = _repetTimes;
this.unScale = _unScale;
this.task = _task;
this.ResetTime();
}
public void ResetTime()
{
this.residueTime = this.delay;
this.residueTimes = this.repetTimes;
}
/// <summary>
/// 设置Time
/// </summary>
/// <param name="_unscaledDeltaTime">Time.unscaledDeltaTime</param>
/// <param name="_deltaTime">Time.deltaTime</param>
public void SetDeltaTime(float _unscaledDeltaTime, float _deltaTime)
{
unscaledDeltaTime = _unscaledDeltaTime;
deltaTime = _deltaTime;
}
public bool Update()
{
this.residueTime -= (this.unScale == true ? unscaledDeltaTime : deltaTime);
if (this.residueTime <= 0f)
{
try
{
this.task();
}
catch (Exception e)
{
LogSystem.LogError(e.ToString());
}
if (this.repetTimes > 0)
{
this.residueTimes--;
if (this.residueTimes <= 0)
{
return true;
}
else
{
this.residueTime = this.delay;
}
}
else if (this.repetTimes == -1)
{
this.residueTime = this.delay;
}
else
{
return true;
}
}
return false;
}
}
需要注意的是由于这个是并行运行的Unity不允许在子线程中调用Time.unscaledDeltaTime, Time.deltaTime因此时间参数unscaledDeltaTime、deltaTime需要由主线程中传入:
this.timeNotifier.SetDeltaTime(Time.unscaledDeltaTime, Time.deltaTime);
逐步迭代游戏基础框架,弄好之后再上传源码工程文件。部分核心代码