【Unity实战|热更】Addressable读取SO文件报错解决

情景再现

假定你有一个Unity工程,使用了HybridCLR和Addressable,SO文件存放在Addressable中。热更加载后进入游戏场景出现了SO文件读取报错:

复制代码
UnityEngine.AddressableAssets.InvalidKeyException: Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown. No Asset found with for Key=Inventory Model Database. Key exists as Type=System.Object, which is not assignable from the requested Type=InventorySystem.Models.InventoryModelDatabase
UnityEngine.AddressableAssets.Addressables:LoadAssetAsync(Object)

可能原因

读取SO文件时,文件绑定的脚本并没有成功还原出来。见官方文档。

解决办法

加载SO文件的代码时不要声明具体的类型,改用System.Object,成功后进行强转。

Before:

cs 复制代码
Addressables.LoadAssetAsync<InventoryModelDatabase>("Inventory Model Database").Completed += handle =>
			{
				if (handle.Status == AsyncOperationStatus.Succeeded)
				{
					_inventoryModelDatabase = handle.Result;
					Debug.Log($"[{GetType()}] Inventory Model Database loaded!");
				}
				else
					Debug.LogError($"[{GetType()}] Failed to load Inventory Model Database!");
			};

After:

cs 复制代码
Addressables.LoadAssetAsync<System.Object>("Inventory Model Database").Completed += handle =>
			{
				if (handle.Status == AsyncOperationStatus.Succeeded)
				{
					_inventoryModelDatabase = handle.Result as InventoryModelDatabase;
					Debug.Log($"[{GetType()}] Inventory Model Database loaded!");
				}
				else
					Debug.LogError($"[{GetType()}] Failed to load Inventory Model Database!");
			};

问题解决。

相关推荐
598866753@qq.com3 小时前
Codex与Unity
unity·游戏引擎
淡海水4 小时前
01-03-认知篇-C#内存模型深度解析
unity·c#·游戏引擎·.net·gc
警醒与鞭策13 小时前
Direct3D 12 中的内存管理
3d·游戏引擎·direct3d
淡海水17 小时前
16-02-C#常用数据结构源码-附录B-源码索引速查
unity·c#·游戏引擎·il2cpp
速易达网络18 小时前
无人机远程操控仿真
游戏引擎·cocos2d
郝学胜-神的一滴19 小时前
游戏引擎原理与实践 02:揭开3A游戏背后的技术面纱
开发语言·计算机网络·程序人生·游戏·游戏引擎
警醒与鞭策1 天前
【无标题】
android·unity·性能优化·游戏引擎·perforce
zhchyun20081 天前
【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(10)
ui·unity·游戏引擎
地狱为王1 天前
Unity使用NVIDIA的Audio2Face驱动口型
unity·游戏引擎
ebiobiz1 天前
STM32F4 Unity 单元测试与多次测试失败率统计详细步骤
stm32·unity·单元测试