Unity反序列化为脚本对象 [英] Unity Deserialize Into Scriptable Object
问题描述
有人知道为什么下面的代码将返回错误
Does anyone know why this code below will return the error
ArgumentException: Cannot deserialize JSON to new instances of type 'CatalogueList.'
UnityEngine.JsonUtility.FromJson[CatalogueList]
我的目录列表存在于我的资产中,我可以很好地序列化并上传到我的服务器,我试图下载我的文件并用json填写所有字段.
My Catalogue list lives in my assets and i can serialize and upload to my server perfectly fine, im trying to download my file and fill in all fields with the json.
这是代码.
void AddDownloadedItems(string text, CatalogueList list)
{
CatalogueList inventoryItemList = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/CatalogueItem.asset", typeof(CatalogueList)) as CatalogueList;
list = JsonUtility.FromJson<CatalogueList>(text);
}
但是正如我说的那样,它只会返回错误?
But as i say it will just return the error?
CatalogueItemList代码
CatalogueItemList Code
public class CatalogueList : ScriptableObject {
public List<CatalogueItem> itemList;
}
目录项目代码
[System.Serializable] // Our Representation of an InventoryItem
public class CatalogueItem
{
public string databaseID;
public string itemName = "New Item";
public enum PrizeMachine { Bronze, Silver, Gold, Platinum };
public PrizeMachine myMachine;
public Texture2D itemThumb = null;
public Texture2D itemIcon = null;
public string itemThumbName;
public string itemIconName;
public string shortDescripion;
public string fullDescription;
public int priceInBronze;
public int priceInSilver;
public int priceInGold;
public int priceInPlatinum;
}
推荐答案
请改用ToJsonOverwrite
!
请注意,JSON序列化器API支持MonoBehaviour和ScriptableObject子类以及普通结构/类.但是,在将JSON反序列化为MonoBehaviour或ScriptableObject的子类时,必须使用FromJsonOverwrite;不支持FromJson,它将引发异常.
Note that the JSON Serializer API supports MonoBehaviour and ScriptableObject subclasses as well as plain structs/classes. However, when deserializing JSON into subclasses of MonoBehaviour or ScriptableObject, you must use FromJsonOverwrite; FromJson is not supported and will throw an exception.
https://docs.unity3d.com/Manual/JSONSerialization.html
那么对你来说
JsonUtility.FromJsonOverwrite(text, list);
请注意,这不是一成不变的方法,它会覆盖您的对象,但无论如何似乎都是您的意图.
Note that this is not an immutable method and will overwrite your object, but it seems like that was your intention anyway.
这篇关于Unity反序列化为脚本对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!