FPS.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2016 Nibiru. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. using UnityEngine;
  15. namespace NXR.Samples
  16. {
  17. [RequireComponent(typeof(TextMesh))]
  18. public class FPS : MonoBehaviour
  19. {
  20. private TextMesh textField;
  21. private float fps = 60;
  22. void Start()
  23. {
  24. textField = GetComponent<TextMesh>();
  25. }
  26. private int lastFPS = -1;
  27. void Update()
  28. {
  29. int fps = calculateFPS();
  30. if (fps != lastFPS)
  31. {
  32. string text = " FPS: " + fps + " fps";
  33. if (textField != null)
  34. {
  35. textField.text = text;
  36. }
  37. }
  38. }
  39. private int calculateFPS()
  40. {
  41. float interp = Time.deltaTime / (0.5f + Time.deltaTime);
  42. float currentFPS = 1.0f / Time.deltaTime;
  43. fps = Mathf.Lerp(fps, currentFPS, interp);
  44. return Mathf.RoundToInt(fps);
  45. }
  46. private void OnDestroy()
  47. {
  48. Debug.Log("FPS.OnDestroy");
  49. }
  50. }
  51. }