using UnityEngine; using UnityEngine.UI; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using System.Collections.Generic; using UnityEngine.SceneManagement; namespace AdaptUI { public class AddressableImageLoader : MonoBehaviour { public enum DeviceType { Auto, iPhone, iPad } [Header("设备类型 (Auto = 自动检测)")] public DeviceType selectedDevice = DeviceType.Auto; public string resourceKey = "LoginBG"; // Addressable 资源 Key private void Awake() { LoadImage(); // 运行时加载 // SceneManager.sceneLoaded += OnSceneLoaded; // 监听场景切换 } private void OnDestroy() { //SceneManager.sceneLoaded -= OnSceneLoaded; } // private void OnSceneLoaded(Scene scene, LoadSceneMode mode) // { // Debug.Log($"📌 [Runtime] 场景切换: {scene.name}, 重新加载 UI"); // LoadImage(); // } public void LoadImage() { if (string.IsNullOrEmpty(resourceKey)) { Debug.LogWarning("⚠️ 资源 Key 为空,请在 Inspector 面板中输入 Key!"); return; } string label = GetDeviceLabel(); Debug.Log($"📌 加载资源 Key:{resourceKey},Label:{label}"); Addressables.LoadAssetsAsync(new List { resourceKey, label }, null, Addressables.MergeMode.Intersection) .Completed += OnSpriteLoaded; } private void OnSpriteLoaded(AsyncOperationHandle> handle) { if (handle.Status == AsyncOperationStatus.Succeeded && handle.Result.Count > 0) { ApplySprite(handle.Result[0]); } else { Debug.LogError("⚠️ 图片加载失败或未找到匹配的资源!"); } } private void ApplySprite(Sprite sprite) { Image image = GetComponent(); if (image != null) image.sprite = sprite; } // private string GetDeviceLabel() // { // if (selectedDevice == DeviceType.iPad) return "iPad"; // if (selectedDevice == DeviceType.iPhone) return "iPhone"; // float aspectRatio = (float)Screen.width / Screen.height; // Debug.Log($"📌 运行时计算屏幕分辨率: width = {Screen.width}, height = {Screen.height}, aspectRatio = {aspectRatio}"); // return aspectRatio < 1.4f ? "iPad" : "iPhone"; // } private string GetDeviceLabel() { if (selectedDevice == DeviceType.iPad) return "iPad"; if (selectedDevice == DeviceType.iPhone) return "iPhone"; DeviceTypeHelper.DeviceType detectedType = DeviceTypeHelper.DetectDeviceType(); // Debug.Log($"📌 运行时设备检测结果: {detectedType}"); return detectedType == DeviceTypeHelper.DeviceType.iPad ? "iPad" : "iPhone"; } } }