[Unity]CSV與Unity與ScriptableObject(1/3)
為什麼會選擇用csv
最近在使用ScriptableObject總會遇見一些小困擾,就是如果ScriptableObject的欄位有變更,像是更改欄位的名字之類的,他所參照的資源又會不見了,如果不小心動到又要重新拉資源過去實屬麻煩,所以我想在表單定義好各數值,再匯進Unity,而且這樣對於企畫人員也會比較方便。
準備表單
為了方便講解,我直接使用我自己的遊戲專案AMOS裡的道具資料。
直接使用GoogleSheet就可以了,方便好編輯的表單網頁,又可以輸出csv檔,對於沒有excel
的人還是個不錯的選擇。
那麼,準備好表單後我們就輸出成csv檔吧,選擇檔案->下載逗號分隔值檔案就可以匯出csv檔了。
我們使用內建的筆記本來打開csv檔案看看,可以很明確的來了解文件的格式是怎麼樣的,欄與欄之間用逗號來隔開,列與列之間則是單純的換行。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 道具的資料
/// </summary>
[CreateAssetMenu(fileName = "Item", menuName = "ScriptableObjects/Item")]
public class Item : ScriptableObject
{
/// <summary>
/// 道具的名字
/// </summary>
[Header("道具的名字")]
public string ItemName;
/// <summary>
/// 道具的介紹
/// </summary>
[Header("道具的介紹")]
public string Introduce;
/// <summary>
/// 道具的ID
/// </summary>
[Header("道具的ID")]
public int ItemID;
/// <summary>
/// 價格
/// </summary>
[Header("價格")]
public int Price;
/// <summary>
/// 這道具的種類
/// </summary>
[Header("種類")]
public ItemType Type;
/// <summary>
/// 這道具的圖片
/// </summary>
[Header("道具相片")]
public Sprite image;
/// <summary>
/// 道具的總類
/// </summary>
public enum ItemType
{
HpPotion,
SpPotion,
ResurrectStone,
BuffPotion,
MonsterDrop
}
}
這樣就可以使用右鍵在Project視窗內新增自己的ScriptableObject了新建好的資源就會長這樣,只要使用列舉(Enum),就可以在Inspector內產生類似選單的效果ScriptableObject的清單
有了資源檔後我們也需要準備可以裝該種資源的容器,這裡我使用的是清單(list)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 道具清單的資料
/// </summary>
[CreateAssetMenu(fileName = "ItemList", menuName = "ScriptableObjects/ItemList")]
public class ItemList : ScriptableObject
{
/// <summary>
/// 系統內部有的道具的清單
/// </summary>
[Header("系統內部有的道具的清單")]
public List<Item> Items = new List<Item>();
private List<Item> _items = new List<Item>();
public ItemList()
{
_items = Items;
}
public Item FindItem(int id)
{
foreach (Item item in _items)
{
if (item.ItemID == id)
{
return item;
}
}
Debug.LogWarning("系統內找不到那個道具");
return null;
}
}
我順便把要透過ID來查找該資源的功能寫在裡面,這樣到時候如果需要透過ID來獲得特定資源會比教方便。當然新增檔案的方式和普通的ScriptableObject是一樣的,新增完資源清單檔案的Insperctor會長這樣。
新建好的資源就會長這樣,只要使用列舉(Enum),就可以在Inspector內產生類似選單的效果
ScriptableObject的清單
有了資源檔後我們也需要準備可以裝該種資源的容器,這裡我使用的是清單(list)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 道具清單的資料
/// </summary>
[CreateAssetMenu(fileName = "ItemList", menuName = "ScriptableObjects/ItemList")]
public class ItemList : ScriptableObject
{
/// <summary>
/// 系統內部有的道具的清單
/// </summary>
[Header("系統內部有的道具的清單")]
public List<Item> Items = new List<Item>();
private List<Item> _items = new List<Item>();
public ItemList()
{
_items = Items;
}
public Item FindItem(int id)
{
foreach (Item item in _items)
{
if (item.ItemID == id)
{
return item;
}
}
Debug.LogWarning("系統內找不到那個道具");
return null;
}
}
我順便把要透過ID來查找該資源的功能寫在裡面,這樣到時候如果需要透過ID來獲得特定資源會比教方便。
當然新增檔案的方式和普通的ScriptableObject是一樣的,新增完資源清單檔案的Insperctor會長這樣。
留言
張貼留言