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

问题解决。

相关推荐
Magnum Lehar2 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
动感光博3 小时前
Unity序列化字段、单例模式(Singleton Pattern)
unity·单例模式·c#
虾球xz3 小时前
游戏引擎学习第290天:完成分离渲染
c++·人工智能·学习·游戏引擎
虾球xz3 小时前
游戏引擎学习第285天:“Traversables 的事务性占用”
c++·学习·游戏引擎
虾球xz4 小时前
游戏引擎学习第280天:精简化的流式实体sim
数据库·c++·学习·游戏引擎
FAREWELL000754 小时前
Unity基础学习(十五)核心系统——音效系统
学习·unity·c#·游戏引擎
虾球xz5 小时前
游戏引擎学习第281天:在房间之间为摄像机添加动画效果
c++·人工智能·学习·游戏引擎
向宇it6 小时前
【unity游戏开发——编辑器扩展】使用MenuItem自定义菜单栏拓展
开发语言·ui·unity·c#·编辑器·游戏引擎
动感光博6 小时前
Unity碰撞检测(射线投射、胶囊体投射)、交互(图层、掩码)
unity·c#·游戏引擎·游戏程序·动画
benben0448 小时前
Unity3D仿星露谷物语开发44之收集农作物
前端·游戏·unity·游戏引擎