[英]How to optimise countdown timer?
尊敬的stackoverflow社区,
我有倒数计时器,可以加倍计时,但现在我遇到了问题,因为我的代码在游戏中可以正常工作,但是当计时器处于活动状态时,游戏滞后了,不是太多,但是任何滞后对我的游戏都没有好处,因为玩家需要玩平稳,没有任何未优化的组件。
我有这个代码,我敢打赌游戏会滞后,因为代码在更新方法中(我试图将其放在游戏管理器脚本中,但是计时器不会倒数,所以这不是解决方案)
这是代码(感谢stackoverflow用户@siusiulala,他为我编写了工作代码),但似乎需要使用其他方法或某些东西,因为当内部有倒数计时时Update方法的运行性能。
private void Update(){ if (isDoublePoints) { // Countdown the timer with update time powerUpTimer -= Time.deltaTime; Debug.Log("TIMER ISS " + powerUpTimer); if (powerUpTimer <= 0) { // End of power up time isDoublePoints = false; } } } public void OnPickPowerUp(float buffTime) { powerUpTimer += buffTime; }
我希望有人能给落后的解决方案,因为我看到很多具有加电系统的游戏,里面没有任何落后的东西...
谢谢stackoverflow,没有你,我的游戏将永远不会结束:)
根据我的经验, Debug.Log()
是一种非常昂贵的方法。 每帧调用时将导致延迟。 因此,我的IDE甚至在Update()
突出显示Debug.Log()
用法作为警告。 仅将此方法用于调试,然后删除。
如果您希望能够看到计时器值,请将[SerializeField]
属性添加到您的字段中,该属性将显示在检查器中。
假设您使用的是Unity 2018.x,则可以通过选择Window-Analysis-Profiler来使用分析器。 它记录处理花费的时间,并帮助定位瓶颈。
Debug.Log
关于Debug.Log
的回答是正确的。
使用[SerializeField]
可能被某些人视为肮脏而懒惰的黑客。 由于它具有现在序列化的副作用,这意味着该值存储在资产中。 这还不错,但是如果您确切的话,则不应使用将在运行时更改的字段来完成操作。
相反,您可以简单地转到检查器,打开上下文菜单并将其设置为“ Debug
模式”。
这使得Inspector不使用Custom EditorScripts,而是显示所有(可Serializable
类型的)私有字段。
例如, Transform
组件
但是方式比使用更高效的Update
方法具有标志都将是相当使用Coroutines
。
可以启动协程并在Update
方法中并行运行(每帧之后),但好处是:协程完成时-协程完成并且不再继续检查每一帧的bool
标志。
因此,每当您启动PowerUp而不是将标志设置为true
都应使用
StartCoroutine(PowerUpRoutine());
并执行像
private IEnumerator PowerUpRoutine()
{
isDoublePoints = true;
while(powerUpTimer > 0)
{
// Countdown the timer with update time
powerUpTimer -= Time.deltaTime;
//Debug.Log("TIMER ISS " + powerUpTimer);
// yield in simple words makes Unity "pause"
// the execution here, render this frame and continue from here
// in the next frame
yield return null;
}
// End of power up time
isDoublePoints = false;
}
public void OnPickPowerUp(float buffTime)
{
powerUpTimer += buffTime;
// avoid concurrent routines
if(!isDoublePoints) StartCoroutine(PowerUpRoutine());
}
为了在游戏中显示它,您可以使用Text
或TextMeshPro
并设置文本,例如
[SerializeField] private Text _text;
private IEnumerator PowerUpRoutine()
{
isDoublePoints = true;
while(powerUpTimer > 0)
{
// Countdown the timer with update time
powerUpTimer -= Time.deltaTime;
//Debug.Log("TIMER ISS " + powerUpTimer);
// set the text of the Text component to display the value
// for the $ symbol google for "c# string interpolation"
_text.text = $"TIMER IS {powerUpTimer:00.00}";
// yield in simple words makes Unity "pause"
// the execution here, render this frame and continue from here
// in the next frame
yield return null;
}
// End of power up time
isDoublePoints = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.