BITKit/Src/Unity/Scripts/Assets/AddressableHelper.cs

91 lines
2.4 KiB
C#

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<ulong,string> PathsById { get; } = new Dictionary<ulong, string>();
public static T Get<T>(ulong id) where T : Object
{
var task = YooAssets.LoadAssetAsync<T>(PathsById[id]);
task.WaitForAsyncComplete();
return task.AssetObject.As<T>();
}
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<AddressableHelper>($"开始注册:{obj}的资源");
var package = YooAssets.GetPackage(obj);
var assetInfos = package.GetAssetInfos(nameof(IAddressable));
var reportBuilder = new StringBuilder();
foreach (var x in assetInfos)
{
var asyncHandle = YooAssets.LoadAssetAsync(x.AssetPath);
await asyncHandle;
if (asyncHandle.AssetObject is IAddressable addressable)
{
if (PathsById.TryAdd(addressable.AddressableId, addressable.AddressablePath) is false)
{
var existing = PathsById[addressable.AddressableId];
BIT4Log.Warning<AddressableHelper>($"{addressable.AddressablePath}的Id:{addressable.AddressableId}已被注册为{existing}");
}
reportBuilder.AppendLine($"{addressable.AddressablePath}的Id:{addressable.AddressableId}");
}
}
BIT4Log.Log<AddressableHelper>($"注册:{obj}的资源完成,耗时:{stopWatcher.ElapsedMilliseconds}ms");
BIT4Log.Log<AddressableHelper>(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);
}
}
}
}