using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using AYellowpaper.SerializedCollections; using BITKit.IO; using Cysharp.Threading.Tasks; using UnityEngine; using YooAsset; using Object = UnityEngine.Object; using Random = UnityEngine.Random; #if UNITY_EDITOR using UnityEditor; #endif namespace BITKit { public class AddressableHelper:MonoBehaviour { private static IDictionary PathsById { get; } = new Dictionary(); public static T Get(ulong id) where T : Object { var task = YooAssets.LoadAssetAsync(PathsById[id]); task.WaitForAsyncComplete(); return task.AssetObject.As(); } private void Start() { PathsById.Clear(); YooAssetUtils.OnPackageRegistered += OnRegister; foreach (var registeredResource in YooAssetUtils.RegisteredResourcePackages) { OnRegister(registeredResource.PackageName); } destroyCancellationToken.Register(() => { YooAssetUtils.OnPackageRegistered -= OnRegister; }); } private static async void OnRegister(string obj) { Stopwatch stopWatcher = new(); stopWatcher.Start(); BIT4Log.Log($"开始注册:{obj}的资源"); var package = YooAssets.GetPackage(obj); var assetInfos = package.GetAssetInfos(nameof(IAddressable)); BIT4Log.Log($"正在解析:{assetInfos.Length}个资源"); var reportBuilder = new StringBuilder(); foreach (var x in assetInfos) { var asyncHandle = YooAssets.LoadAssetAsync(x.AssetPath); await asyncHandle; var addressable = asyncHandle.AssetObject switch { IAddressable a=>a, MonoBehaviour m=>m.GetComponent(), GameObject g=>g.GetComponent(), _ => null }; if (addressable is null) continue; if (PathsById.TryAdd(addressable.AddressableId, addressable.AddressablePath) is false) { var existing = PathsById[addressable.AddressableId]; BIT4Log.Warning($"{addressable.AddressablePath}的Id:{addressable.AddressableId}已被注册为{existing}"); } reportBuilder.AppendLine($"{addressable.AddressablePath}的Id:{addressable.AddressableId}"); } BIT4Log.Log($"注册:{obj}的资源完成,耗时:{stopWatcher.ElapsedMilliseconds}ms"); BIT4Log.Log(reportBuilder.ToString()); } } public static class RandomUlong { private static readonly System.Random _random = new(); public static ulong NextUlong { get { var buf = new byte[8]; _random.NextBytes(buf); return BitConverter.ToUInt64(buf, 0); } } } }