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

问题解决。

相关推荐
孟无岐15 小时前
【Laya】Laya 类使用说明
typescript·游戏引擎·游戏程序·laya
在路上看风景17 小时前
1.2 Unity资源分类
unity·游戏引擎
one named slash17 小时前
BMFont在Unity中生成艺术字
unity·游戏引擎
郝学胜-神的一滴19 小时前
图形学中的纹理映射问题:摩尔纹与毛刺的深度解析
c++·程序人生·unity·游戏引擎·图形渲染·unreal engine
在路上看风景19 小时前
10. CPU-GPU协作渲染
unity
程序员agions19 小时前
Unity 游戏开发邪修秘籍:从入门到被策划追杀的艺术
unity·cocoa·lucene
JIes__20 小时前
Unity(一)——场景切换、退出游戏、鼠标隐藏锁定...
unity·游戏引擎
NIKITAshao1 天前
Unity URP Volume组件详解(笔记)
unity·游戏引擎
lingxiao168881 天前
WebApi详解+Unity注入--下篇:Unity注入
unity·c#·wpf
世洋Blog1 天前
面经-CPU、内存、GPU的性能优化
unity·性能优化