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

问题解决。

相关推荐
璞瑜无文1 小时前
Unity 游戏开发之入门
unity·游戏引擎
一线灵3 小时前
Axmol 引擎系列教程之 - 如何切换引擎依赖库镜像
游戏引擎
毛甘木3 小时前
Unity ComputeShader 基础语法与使用教程
unity·computeshader
小清兔4 小时前
一个unity中URP的环境下旋转天空盒的脚本(RotationSky)
开发语言·数据库·学习·程序人生·unity·c#·游戏引擎
EQ-雪梨蛋花汤4 小时前
【Unity笔记】 WorldStreamer2指南——针对大世界的流式加载与优化
笔记·unity·游戏引擎
迪普阳光开朗很健康4 小时前
适用Unity的AndroidStudio项目自动修改打包文件名称的方案
unity·游戏引擎
米芝鱼4 小时前
Unity自定义按钮
算法·ui·unity·游戏引擎·编辑器扩展
米芝鱼5 小时前
Unity自定义TextImage,鼠标悬浮显示信息
算法·ui·unity·编辑器·游戏引擎·图形渲染
阿Q说代码6 小时前
开篇:从理论到实践,体验openEuler嵌入式开发全流程
unity·游戏引擎
zxb@hny7 小时前
Hazel游戏引擎学习
学习·游戏引擎