iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

深入淺出做中學Unity系列 第 8

Unity - 關於保留美好回憶這件小事(3)

接續上一篇的關於保留美好回憶這件小事(2),那麼在有了影像之後,該如何留存文字及數據呢?讓我繼續娓娓道來 :

此篇重點主要是著重在Unity遊戲中的數據存取,以及如何做資料的處理

我們先來假設我們今天要做的一個場景是人物基本資訊,而人物的資訊如下面所示

  1. 名稱 (name)
  2. 等級 (level)
  3. 攻擊力 (attack)
  4. 防禦力 (defence)

為此我們要新增一個class,裡面包含這些物件屬性的類別

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]

public class player {

    public string name;

    public int level;

    public float attack;

    public float defence;

}

接下來就是要做建立資料的動作,先開新的一個script

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class SaveData : MonoBehaviour {
    void Start(){
        //建立一個player物件
        player p1 = new player();

        //設置各屬性

        p1.name = "Tom";

        p1.level = 50;

        p1.attack = 600;

        p1.defence = 200;

        //將此player裡面的屬性轉成string(json格式)
        string saveString = JsonUtility.ToJson(p1);
    }

}

做好此動作後就是要將json格式的string存到asset裡面,我們先在unity 專案內部新增一個GameJSONData的資料夾以供儲存地使用,接著將剛剛的code多加這幾行 :

//將字串saveString存到硬碟中

  StreamWriter file = new           
  StreamWriter(System.IO.Path.Combine("Assets/GameJSONData", "Player1.json"));

  file.Write(saveString);
  file.Close();

如此一來整個架構會變成 :

using System.Collections;

using System.Collections.Generic;

using System.IO;

using UnityEngine;

 

public class SaveData : MonoBehaviour {

 

    void Start(){

        //建立一個player物件

        player p1 = new player();

 

        //設置p1內的各屬性

        p1.name = "Tom";

        p1.level = 50;

        p1.attack = 600;

        p1.defence = 200;

       

        //將此player裡面的屬性轉成string(json格式)

        string saveString = JsonUtility.ToJson(p1);

       

        //將字串saveString存到硬碟中

        StreamWriter file = new StreamWriter(System.IO.Path.Combine("Assets/GameJSONData", "Player1.json"));

        file.Write(saveString);

        file.Close();

    }

}

另外一方面,若是要在人物身上增加他所擁有的裝備我們可以在新增一個class叫做equipment(甚麼名字都行)

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

 

[System.Serializable]

public class equipment{

    public string equipmentName;

    public int limitLevel;

    public int attack;

}

而在人物player.cs這邊,我們新增一個List屬性

public List equipment = new List();

在SaveData的code我們新增下面幾段

equipment eq1 = new equipment();

        eq1.attack = 87;

        eq1.limitLevel = 50;

        eq1.equipmentName = "Excalibur";

        p1.equipment.Add(eq1);

這樣就可以在GameJSONData的資料夾中發現有一個新的json檔,裡面的文字如下

{"name":"Tom","level":50,"attack":600.0,"defence":200.0,"equipment":[{"equipmentName":"Excalibur","limitLevel":50,"attack":87}]}

可以發現很順利的把角色資訊存進去了!


上一篇
Unity – 關於保留美好回憶這件小事(2)
下一篇
Unity3D - 遊戲角色感知三兩事
系列文
深入淺出做中學Unity9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言