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

问题解决。

相关推荐
小贺儿开发7 小时前
Unity3D 八大菜系连连看
游戏·unity·互动·传统文化
在路上看风景7 小时前
25. 屏幕像素和纹理像素不匹配
unity
ۓ明哲ڪ8 小时前
Unity功能——创建新脚本时自动添加自定义头注释
unity·游戏引擎
熬夜敲代码的小N8 小时前
Unity大场景卡顿“急救包”:从诊断到落地的全栈优化方案
java·unity·游戏引擎
派葛穆10 小时前
Unity-realvirtual-S7通讯快速配置(未完结)
unity·游戏引擎
w-白兰地20 小时前
【Addressable远端加载资源】
unity·addressable·资源加载
小张不爱写代码1 天前
[Unity 技巧] 如何自定义 Inspector 变量显示名称 (CustomLabel)
unity·游戏引擎
Sator11 天前
Unity开发中常用的随机方法扩展
unity
dzj20211 天前
Unity中使用LLMUnity遇到的问题(五)——主要脚本的继承关系+用DuckDB对知识库升级的思考
unity·向量数据库·向量搜索·duckdb·llmunity
地狱为王1 天前
Unity使用Spleeter分离人声和伴奏
unity·游戏引擎·spleeter