AddressableImageLoader.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.AddressableAssets;
  4. using UnityEngine.ResourceManagement.AsyncOperations;
  5. using System.Collections.Generic;
  6. using UnityEngine.SceneManagement;
  7. namespace AdaptUI
  8. {
  9. public class AddressableImageLoader : MonoBehaviour
  10. {
  11. public enum DeviceType { Auto, iPhone, iPad }
  12. [Header("设备类型 (Auto = 自动检测)")]
  13. public DeviceType selectedDevice = DeviceType.Auto;
  14. public string resourceKey = "LoginBG"; // Addressable 资源 Key
  15. private void Awake()
  16. {
  17. LoadImage(); // 运行时加载
  18. // SceneManager.sceneLoaded += OnSceneLoaded; // 监听场景切换
  19. }
  20. private void OnDestroy()
  21. {
  22. //SceneManager.sceneLoaded -= OnSceneLoaded;
  23. }
  24. // private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
  25. // {
  26. // Debug.Log($"📌 [Runtime] 场景切换: {scene.name}, 重新加载 UI");
  27. // LoadImage();
  28. // }
  29. public void LoadImage()
  30. {
  31. if (string.IsNullOrEmpty(resourceKey))
  32. {
  33. Debug.LogWarning("⚠️ 资源 Key 为空,请在 Inspector 面板中输入 Key!");
  34. return;
  35. }
  36. string label = GetDeviceLabel();
  37. Debug.Log($"📌 加载资源 Key:{resourceKey},Label:{label}");
  38. Addressables.LoadAssetsAsync<Sprite>(new List<object> { resourceKey, label }, null, Addressables.MergeMode.Intersection)
  39. .Completed += OnSpriteLoaded;
  40. }
  41. private void OnSpriteLoaded(AsyncOperationHandle<IList<Sprite>> handle)
  42. {
  43. if (handle.Status == AsyncOperationStatus.Succeeded && handle.Result.Count > 0)
  44. {
  45. ApplySprite(handle.Result[0]);
  46. }
  47. else
  48. {
  49. Debug.LogError("⚠️ 图片加载失败或未找到匹配的资源!");
  50. }
  51. }
  52. private void ApplySprite(Sprite sprite)
  53. {
  54. Image image = GetComponent<Image>();
  55. if (image != null) image.sprite = sprite;
  56. }
  57. // private string GetDeviceLabel()
  58. // {
  59. // if (selectedDevice == DeviceType.iPad) return "iPad";
  60. // if (selectedDevice == DeviceType.iPhone) return "iPhone";
  61. // float aspectRatio = (float)Screen.width / Screen.height;
  62. // Debug.Log($"📌 运行时计算屏幕分辨率: width = {Screen.width}, height = {Screen.height}, aspectRatio = {aspectRatio}");
  63. // return aspectRatio < 1.4f ? "iPad" : "iPhone";
  64. // }
  65. private string GetDeviceLabel()
  66. {
  67. if (selectedDevice == DeviceType.iPad) return "iPad";
  68. if (selectedDevice == DeviceType.iPhone) return "iPhone";
  69. DeviceTypeHelper.DeviceType detectedType = DeviceTypeHelper.DetectDeviceType();
  70. // Debug.Log($"📌 运行时设备检测结果: {detectedType}");
  71. return detectedType == DeviceTypeHelper.DeviceType.iPad ? "iPad" : "iPhone";
  72. }
  73. }
  74. }