unity:使協(xié)程不受幀率干擾的影響

(個人記錄,記得很隨便)

提出問題
這是一個unity的協(xié)程方法,可以物體從小到大平滑過渡縮放
很簡單的,小學二年級都可以寫出來
? ?private IEnumerator Scale(float speed)
? ?{
? ? ? ?transform.localScale = Vector3.zero;
? ? ? ?while (localScale.magnitude - transform.localScale.magnitude > 0.01f)
? ? ? ?{
? ? ? ? ? ?float y = Mathf.SmoothStep(transform.localScale.y, localScale.y, Time.fixedDeltaTime * speed);
? ? ? ? ? ?transform.localScale = new Vector3(localScale.x, y, localScale.z);
? ? ? ? ? ?yield return 0;
? ? ? ?}
? ?}
實操發(fā)現(xiàn),這個協(xié)程會受到游戲幀率的影響
我嘗試修復,接連嘗試了deltaTime、fixedTime、unscaledTime、fixedUnscaledTime都無濟于事(修了一上午)

解決問題
后面,我與ChatGPT想到了一個絕妙的方法:
可以考慮使用實際時間(例如使用Time.time)進行縮放過渡,而不是依賴于幀率?。?/strong>
這是最終的代碼,效果非常好:
? ?private IEnumerator Scale(float speed)
? ?{
? ? ? ?transform.localScale = Vector3.zero;
? ? ? ?float startTime = Time.time;
? ? ? ?float duration = (localScale.magnitude - transform.localScale.magnitude) / speed;
? ? ? ?while (Time.time - startTime < duration)
? ? ? ?{
? ? ? ? ? ?float t = (Time.time - startTime) / duration;
? ? ? ? ? ?float y = Mathf.SmoothStep(0f, localScale.y, t);
? ? ? ? ? ?transform.localScale = new Vector3(localScale.x, y, localScale.z);
? ? ? ? ? ?yield return null;
? ? ? ?}
? ? ? ?transform.localScale = localScale;
? ?}
標簽: