DpiManager.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace TheraBytes.BetterUi
  6. {
  7. [Serializable]
  8. public class DpiManager
  9. {
  10. #if UNITY_WEBGL
  11. [System.Runtime.InteropServices.DllImport("__Internal")]
  12. private static extern double GetDPI();
  13. #endif
  14. [Serializable]
  15. public class DpiOverride
  16. {
  17. [SerializeField] float dpi = 96;
  18. [SerializeField] string deviceModel;
  19. public float Dpi { get { return dpi; } }
  20. public string DeviceModel { get { return deviceModel; } }
  21. public DpiOverride(string deviceModel, float dpi)
  22. {
  23. this.deviceModel = deviceModel;
  24. this.dpi = dpi;
  25. }
  26. }
  27. [SerializeField]
  28. List<DpiOverride> overrides = new List<DpiOverride>();
  29. public float GetDpi()
  30. {
  31. DpiOverride ov = overrides.FirstOrDefault(o => o.DeviceModel == SystemInfo.deviceModel);
  32. if (ov != null)
  33. return ov.Dpi;
  34. #if UNITY_WEBGL && !UNITY_EDITOR
  35. try
  36. {
  37. // Fix Web GL Dpi bug (Unity thinks it is always 96 DPI)
  38. return (float)(GetDPI() * 96.0f);
  39. }
  40. catch
  41. {
  42. Debug.LogError("Could not retrieve real DPI. Is the WebGL-DPI-Plugin installed in the project?");
  43. }
  44. #endif
  45. return Screen.dpi;
  46. }
  47. }
  48. }