using UnityEditor; using UnityEngine; using UnityEngine.UI; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; namespace AdaptUI { [CustomEditor(typeof(AddressableImageLoader))] public class AddressableImageLoaderEditor : Editor { private Vector2 lastGameViewSize; private void OnEnable() { //EditorApplication.update += CheckGameViewSizeChange; } private void OnDisable() { //EditorApplication.update -= CheckGameViewSizeChange; } private void CheckGameViewSizeChange() { Vector2 currentSize = GameViewSizeHelper.GetGameViewSize(); if (currentSize != lastGameViewSize) // 仅在尺寸变化时触发 { lastGameViewSize = currentSize; //Debug.Log($"📌 [Editor] Game 视图分辨率变化: {currentSize.x} x {currentSize.y}"); AddressableImageLoader loader = (AddressableImageLoader)target; LoadImageInEditor(loader); // loader.LoadImage(); // 重新加载 UI 资源 } } public override void OnInspectorGUI() { DrawDefaultInspector(); // 默认 Inspector UI AddressableImageLoader loader = (AddressableImageLoader)target; if (GUILayout.Button("🔄 刷新 UI(Editor 模式)")) { LoadImageInEditor(loader); } } public static void LoadImageInEditor(AddressableImageLoader loader) { if (!Application.isPlaying) // 仅在 Editor 模式下执行 { string label = GetDeviceLabel(loader); string key = loader.resourceKey; //Debug.Log($"📌 [Editor] 加载 Addressable 资源: Key = {key}, Label = {label}"); Addressables.LoadAssetsAsync(new[] { key, label }, null, Addressables.MergeMode.Intersection) .Completed += handle => { if (handle.Status == AsyncOperationStatus.Succeeded && handle.Result.Count > 0) { Sprite sprite = handle.Result[0]; Image image = loader.GetComponent(); if (image != null) { Undo.RecordObject(image, "Change Sprite"); // 支持 Undo image.sprite = sprite; Debug.Log($"✅ [Editor] UI 资源已更新: {sprite.name}"); EditorUtility.SetDirty(image); } } else { Debug.LogWarning($"⚠️ [Editor] 未找到匹配的 Addressable 资源! Key={key}, Label={label}"); } }; } } // private static string GetDeviceLabel(AddressableImageLoader loader) // { // if (loader.selectedDevice == AddressableImageLoader.DeviceType.iPad) return "iPad"; // if (loader.selectedDevice == AddressableImageLoader.DeviceType.iPhone) return "iPhone"; // Vector2 gameViewSize = GameViewSizeHelper.GetGameViewSize(); // float aspectRatio = gameViewSize.x / gameViewSize.y; // Debug.Log($"📌 [Editor] 计算 Game 视图分辨率: width = {gameViewSize.x}, height = {gameViewSize.y}, aspectRatio = {aspectRatio}"); // return aspectRatio < 1.4f ? "iPad" : "iPhone"; // 修正判定逻辑 // } private static string GetDeviceLabel(AddressableImageLoader loader) { if (loader.selectedDevice == AddressableImageLoader.DeviceType.iPad) return "iPad"; if (loader.selectedDevice == AddressableImageLoader.DeviceType.iPhone) return "iPhone"; DeviceTypeHelper.DeviceType detectedType = DeviceTypeHelper.DetectDeviceType(); //Debug.Log($"📌 [Editor] 设备检测结果: {detectedType}"); return detectedType == DeviceTypeHelper.DeviceType.iPad ? "iPad" : "iPhone"; } } }