This commit is contained in:
2025-04-23 12:56:20 +08:00
parent b47e96ea9e
commit 8f2e12622d
4 changed files with 56 additions and 26 deletions
@@ -1,6 +1,10 @@
using System;
using System.Collections;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace AibisDream.Framework
{
@@ -10,7 +14,7 @@ namespace AibisDream.Framework
{
#if UNITY_EDITOR
if (!sprite) return "";
// 先读Psd的路径
string psdPath = AssetDatabase.GetAssetPath(sprite);
var psdResPath = GetResourcePath(psdPath);
@@ -25,49 +29,67 @@ namespace AibisDream.Framework
// 提取文件名(不包括扩展名)
var purePath = psdResPath.Substring(0, lastDotIndex);
// 添加后缀
return purePath + "/" + sprite.name;
#else
return null;
#endif
}
private static string GetResourcePath(string absolutePath)
{
const string resourcesFolderName = "Resources/";
int index = absolutePath.IndexOf(resourcesFolderName, StringComparison.Ordinal);
var index = absolutePath.IndexOf(resourcesFolderName, StringComparison.Ordinal);
if (index >= 0)
{
// 获取 "Resources/" 之后的部分
return absolutePath.Substring(index + resourcesFolderName.Length);
}
else
{
return absolutePath;
}
return index >= 0 ? absolutePath[(index + resourcesFolderName.Length)..] : absolutePath;
}
public static Sprite LoadSpriteFromPsd(string path)
{
int lastIndex = path.LastIndexOf('/');
string spriteName = path.Substring(lastIndex + 1);
string resPath = path.Substring(0, lastIndex);
string spriteName = path[(lastIndex + 1)..];
string resPath = path[..lastIndex];
// 加载
var sprites = Resources.LoadAll<Sprite>(resPath);
foreach (var sprite in sprites)
return sprites.FirstOrDefault(sprite => sprite.name == spriteName);
}
public static T LoadAssetSync<T>(string key) where T : UnityEngine.Object
{
T result = null;
var operation = Addressables.LoadAssetAsync<T>(key);
// 运行协程等待加载完成
GameManager.Instance.StartCoroutine(LoadCoroutine(operation, loadedObject => result = loadedObject));
// 等待协程完成(阻塞主线程)
while (!operation.IsDone)
{
if (sprite.name == spriteName)
{
return sprite;
}
// 主动让出一帧
System.Threading.Thread.Sleep(1);
}
return null;
return result;
}
private static IEnumerator LoadCoroutine<T>(AsyncOperationHandle<T> operation, Action<T> onComplete)
where T : UnityEngine.Object
{
yield return operation;
if (operation.Status == AsyncOperationStatus.Succeeded)
{
onComplete?.Invoke(operation.Result);
}
else
{
Debug.LogError("Failed to load addressable");
}
Addressables.Release(operation);
}
}
}