分享一下之前接Xasset的模块Code【仅用于业务参考】
using System;
using System.Collections.Generic;
using System.IO;
using Common;
using Cysharp.Threading.Tasks;
using UnityEngine;
using xasset;
using xasset.example;
using Logger = xasset.Logger;
using Object = UnityEngine.Object;
namespace Resource
{
public class ResourceModule : BaseModule
{
public string Name => "ResourceModule"; // 获取对应模块的名称
public LoadMode loadMode = LoadMode.LoadByRelativePath;
public string[] filters =
{
"Scenes", "Prefabs", "Textures"
};
private static Dictionary<string, Asset> cache = new Dictionary<string, Asset>(); // 存储已加载的资源
public async UniTask BeforeInit()
{
Debug.Log($"{Name} XAsset init start");
Versions.VerifyMode = VerifyMode.Size;
Bundle.AutoUpdate = true;
await Versions.InitializeAsync();
Initialize();
Debug.Log($"{Name} XAsset init finish");
PreLoadResource();
}
public void Initialize()
{
switch (loadMode)
{
case LoadMode.LoadByName:
Manifest.customLoader += LoadByName;
break;
case LoadMode.LoadByNameWithoutExtension:
Manifest.customLoader += LoadByNameWithoutExtension;
break;
default:
Manifest.customLoader = null;
break;
}
}
public void PreLoadResource()
{
// 加载预加载资源
LoadNewAsset<GameObject>("Assets/.prefab");
}
//加载指定资源 path相对路径:Assets/..... type获取的类型
public static T LoadNewAsset<T>(string path) where T : Object
{
if (cache.TryGetValue(path, out var value))
{
return (T)value.asset;
}
value = Asset.Load(path, typeof(T));
if (value != null)
{
cache.Add(path, value);
return (T)value.asset;
}
Debug.Log("LoadNewAsset value is null");
return null;
}
// 卸载指定路径的资源
public static void UnLoadAsset(string path)
{
//引用计数减 1
cache[path].Release();
cache.Remove(path);
}
private string LoadByName(string assetPath)
{
if (filters == null || filters.Length == 0)
{
return null;
}
if (!Array.Exists(filters, assetPath.Contains))
{
return null;
}
var assetName = Path.GetFileName(assetPath);
return assetName;
}
private string LoadByNameWithoutExtension(string assetPath)
{
if (filters == null || filters.Length == 0)
{
return null;
}
if (!Array.Exists(filters, assetPath.Contains))
{
return null;
}
var assetName = Path.GetFileNameWithoutExtension(assetPath);
return assetName;
}
public void Init()
{
// Method intentionally left empty.
}
public void ModuleUpdate()
{
// Method intentionally left empty.
}
public void Resume()
{
// Method intentionally left empty.
}
public void Restart()
{
// Method intentionally left empty.
}
public void OpenModuleDialog()
{
// Method intentionally left empty.
}
public void Pause()
{
// Method intentionally left empty.
}
public void Destroy()
{
cache.Clear();
}
}
}