【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!");
			};

问题解决。

相关推荐
雪儿waii33 分钟前
Unity 中的 InvokeRepeating 详解
unity·游戏引擎
mxwin44 分钟前
Unity Shader 程序化生成:Shader 中的数学宇宙
unity·游戏引擎
雪儿waii2 小时前
Unity 中的 Quaternion(四元数)详解
unity·游戏引擎
RReality2 小时前
【Unity UGUI】ScrollRect 与 Scrollbar 深度用法
unity·游戏引擎
人邮异步社区2 小时前
如何自学游戏引擎的开发?
unity·程序员·游戏引擎
郝学胜-神的一滴4 小时前
[简化版 Games 101] 计算机图形学 05:二维变换下
c++·unity·图形渲染·three.js·opengl·unreal
mxwin17 小时前
Unity URP 热更新兼容性:Shader 在 IL2CPP 打包下的注意事项
unity·游戏引擎
mxwin1 天前
Unity shader中TransformWorldToShadowCoord原理解析
unity·游戏引擎·shader
mxwin1 天前
Unity Shader 中 ShadowCaster的作用和疑问
unity·游戏引擎
mxwin1 天前
Unity Shader中如何学习阴影技术 产生阴影,接受阴影,联级阴影,软阴影
学习·unity·游戏引擎·shader