simplestarの技術ブログ

目的を書いて、思想と試行、結果と考察、そして具体的な手段を記録します。

Unityでクラスをファイルとして保存(シリアライズ)

前置き

ゲーム内で利用しているクラスオブジェクトをそっくりファイルに保存して
次にゲームを起動したときに、そのファイルからクラスオブジェクトを完璧に復元できます。
できる方法があります。

ゲームの状態をセーブして、次にゲームを起動したときにロードする話です。
基本的なゲームの機能ですね。

ファイルの読み書きの書式を学んで、独自にファイルフォーマットを策定して、必要なゲーム情報だけを効率的に保存し、効率的に読み出しできるようにローダーを描く、残念ですがこんなプロ仕様な話は今回は取り扱いません。

今回はタイトルの通り、セーバーもローダーも用意せずに、クラスオブジェクトを渡すとファイルになり、ファイルを渡すとクラスオブジェクトが得られる方法をここでは扱います。

具体的な実装方法

バイナリファイル版

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class BinaryUtil {

    public static void Seialize<T>(string path, T obj)
    {
        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, obj);
        }
    }

    public static T Deserialize<T>(string path)
    {
        T obj;
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            BinaryFormatter f = new BinaryFormatter();
            obj = (T)f.Deserialize(fs);
        }
        return obj;
    }
}

注意点として T に設定するクラスには属性

    [Serializable()]
    public class Chunk {

が必要

Xmlファイル版

using System.IO;
using System.Xml.Serialization;

public class XmlUtil
{
    public static T Seialize<T>(string filename, T data)
    {
        using (var stream = new FileStream(filename, FileMode.Create))
        {
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stream, data);
        }

        return data;
    }

    public static T Deserialize<T>(string filename)
    {
        using (var stream = new FileStream(filename, FileMode.Open))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stream);
        }
    }
}
実装メモ

これでマイクロワールドのチャンクの初期状態をファイルから復元できるようになりました。

f:id:simplestar_tech:20180107133138j:plain