[英]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.