Unity ScriptableObject资源文件序列化存取流程

  如果你在unity编辑器里制作了很多ScriptableObject资源,想通过代码自动化管理,可以使用AssetDataBase API和json序列化做到

  以卡牌游戏为例:

 1 private void LoadAllCards()
 2     {
 3         if (File.Exists(PATH))
 4         {
 5             string json = File.ReadAllText(PATH);
 6             CardData data = JsonUtility.FromJson<CardData>(json);
 7             for (int i = 0; i < data.cards.Length; i++)
 8             {
 9                 CardIdentity card = data.cards[i];
10                 cards.Add(card.ID, card);
11             }
12         }
13         #if UNITY_EDITOR
14         else
15         {
16             SaveAllCard();
17             
18             return;
19         }
20         #endif
21     }

  PATH是路径常量,可以写成Application.dataPath + "你要的文件名"

  #if UNITY_EDITOR  的预处理器指令用于确保文件的保存行为只会在编辑器模式下执行,因为文件不应当在打包发布后再更改

 1     [ContextMenu("序列化所有卡牌")]
 2     private void SaveAllCard()
 3     {
 4         List<CardIdentity> cardAssets = new List<CardIdentity>();        
 5 
 6         string[] locatpaths = new string[] { "Assets/创建的卡牌/[0]", "Assets/创建的卡牌/[1]", "Assets/创建的卡牌/[2]" }; //文件的路径,如果只有一个文件夹就不需要使用数组
 7         
 8         //FindAssets方法找到卡牌的GUID,参数"t:Type"代表要查找的类型,详细使用方法请参考官方文档
 9         string[] guids = AssetDatabase.FindAssets("t:CardIdentity",locatpaths);
10         for (int i = 0; i < guids.Length; i++) //通过找到的GUID得到asset资源,并转化为CardIdentity存入列表
11         {
12             string uid = guids[i];
13             string assetPath = AssetDatabase.GUIDToAssetPath(uid);
14             cardAssets.Add(AssetDatabase.LoadAssetAtPath<CardIdentity>(assetPath));
15         }
16 
17         //可以打印Count检查是否成功获取到
18         //Debug.Log(cardAssets.Count);
19 
20         //使用一个简单类来存储数据
21         CardData data = new CardData
22         {
23             cards = cardAssets.ToArray()
24         };
25 
26         //序列化为json
27         string json = JsonUtility.ToJson(data);
28 
29         //最后用文件C# I/O 保存文件
30         string tempPath = Application.dataPath + "/cardData.json";
31         if (File.Exists(tempPath))
32             File.Delete(tempPath);
33         File.WriteAllText(tempPath, json);
34         //Debug.Log(tempPath);
35     }    
View Code

  对于存储数据的简单类,记得要加上[System.Serializable]特性,这样Unity才能序列化这个类

1     [System.Serializable]
2     private class CardData
3     {
4         public CardIdentity[] cards;
5     }

  最后放上用到的unity AssetDataBase的API文档链接:

FindAsset : https://docs.unity.cn/cn/2018.4/ScriptReference/AssetDatabase.FindAssets.html

LoadAssetAtPath : https://docs.unity.cn/cn/2018.4/ScriptReference/AssetDatabase.LoadAssetAtPath.html

 

posted @ 2023-03-08 17:28  羊行天下  阅读(147)  评论(0编辑  收藏  举报