GlobalFPS.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. using UnityEngine.UI;
  5. namespace Rokid.UXR.Utility
  6. {
  7. public class GlobalFPS : MonoBehaviour
  8. {
  9. private float fpsUpdateTime = 1.0f;
  10. private float passedTime = 0.0f;
  11. private Canvas canvas;
  12. public Text textField;
  13. private void Start()
  14. {
  15. canvas = gameObject.GetComponent<Canvas>();
  16. if (MainCameraCache.mainCamera != null)
  17. {
  18. canvas.renderMode = RenderMode.ScreenSpaceCamera;
  19. canvas.worldCamera = MainCameraCache.mainCamera;
  20. canvas.planeDistance = 3;
  21. if (textField != null)
  22. {
  23. float textFieldWidth = textField.rectTransform.rect.width;
  24. float textFieldHeight = textField.rectTransform.rect.height;
  25. textField.rectTransform.anchoredPosition = new Vector2(Screen.width / 2.0f - 2.3f * textFieldWidth, Screen.height / 2.0f + 2.0f * textFieldHeight);
  26. }
  27. }
  28. SceneManager.sceneLoaded += OnSceneLoaded;
  29. }
  30. private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
  31. {
  32. if (canvas != null && MainCameraCache.mainCamera != null)
  33. {
  34. canvas.worldCamera = MainCameraCache.mainCamera;
  35. }
  36. }
  37. private void OnDestroy()
  38. {
  39. SceneManager.sceneLoaded -= OnSceneLoaded;
  40. }
  41. void LateUpdate()
  42. {
  43. passedTime += Time.smoothDeltaTime;
  44. if (passedTime >= fpsUpdateTime && textField != null)
  45. {
  46. textField.text = "RenderFPS: " + Mathf.RoundToInt(1.0f / Time.smoothDeltaTime);
  47. passedTime = 0.0f;
  48. }
  49. }
  50. }
  51. }