[Unity]CSV與Unity與ScriptableObject(1/3)

 

為什麼會選擇用csv

最近在使用ScriptableObject總會遇見一些小困擾,就是如果ScriptableObject的欄位有變更,像是更改欄位的名字之類的,他所參照的資源又會不見了,如果不小心動到又要重新拉資源過去實屬麻煩,所以我想在表單定義好各數值,再匯進Unity,而且這樣對於企畫人員也會比較方便。

準備表單

為了方便講解,我直接使用我自己的遊戲專案AMOS裡的道具資料。
直接使用GoogleSheet就可以了,方便好編輯的表單網頁,又可以輸出csv檔,對於沒有excel
的人還是個不錯的選擇。

那麼,準備好表單後我們就輸出成csv檔吧,選擇檔案->下載逗號分隔值檔案就可以匯出csv檔了。
我們使用內建的筆記本來打開csv檔案看看,可以很明確的來了解文件的格式是怎麼樣的,欄與欄之間用逗號來隔開,列與列之間則是單純的換行

所以我們要讀取的方式也很簡單,先讀取第一列的標題,將其儲存起來,要找各行的資料時依照標題們來判斷就好了。

腳本撰寫

ScriptableObject準備

只要繼承ScrtiprableObject類別就可以簡易地用出自己的SO了,為了讓我們可以新增這個資源物件,我們需要加上Attribute: CreateAssetMenu,如此一來就可以在Project視窗新增這個類別的物件了。
  • FileName指的是新增出來的檔案的檔名
  • MenuName指的是你右鍵時會出來的路徑,你可以自由的命名

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會長這樣。



留言

這個網誌中的熱門文章

[Unity] 關於Android 的環境設定,使用自己的SDK/JDK/NDK

[Godot] Sprite Sheet 使用以及HDR Glow 發光效果

[Godot] 起始之初,編輯器認識:關聯Rider IDE