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

问题解决。

相关推荐
B0URNE15 小时前
【Unity基础详解】(11)Unity核心:输入系统
unity·游戏引擎
世洋Blog17 小时前
Unity开发微信小游戏-减少WASM包体大小
unity·游戏引擎·wasm·微信小游戏
TO_ZRG18 小时前
Unity 通过 NativePlugin 接入Android SDK 指南
android·unity·游戏引擎
jtymyxmz20 小时前
《Unity Shader》10.2.1 镜子效果
unity·游戏引擎
ellis197020 小时前
Unity打开新项目Package相关报错处理记录
unity
微:xsooop1 天前
iOS 上架4.3a 审核4.3a 被拒4.3a 【灾难来袭】
flutter·unity·ios·uniapp
微光守望者1 天前
Unity ScriptableObject详解:优化游戏架构的强大工具
unity·游戏引擎
jtymyxmz1 天前
《Unity Shader》10.2.2 玻璃效果
unity·游戏引擎
zxc2446039341 天前
gpu instancer crowd 动画使用方式
unity
C MIKE1 天前
unity资源下载
unity