ドキュメント

Unity Engine

Unity Engine

カスタムシリアル化

Unity のシリアライザーでサポートされていない追加アイテムをシリアライズする方法。
読み終わるまでの所要時間 7 分最終更新 6日前

Unity のシリアライザーがサポートしないもの (例えば C# ディクショナリ) をシリアライズする場合は、クラスに ISerializationCallbackReceiver インターフェースを実装できます。これにより、Unity がシリアル化とデシリアライズの間のキーなポイントで呼び出すコールバックを実装できます。
シリアル化コールバックを使用すると、シリアル化が難しいデータをランタイムとシリアル化時で異なる表現にすることができます。Unityがデータをシリアライズする直前に、Unityが理解できるデータにTransformできます。Unity がフィールドにデータを書き込んだら、シリアライズされたデータをランタイムに必要な形式に Transform できます。
  1. オブジェクトがシリアライズされようとすると、Unity は
    OnBeforeSerialize()
    コールバックを実行します。このコールバックバックでは、データを Unity が理解できるものにTransformできます。例えば、C# ディクショナリをシリアライズするには、ディクショナリからデータをキーの配列と値の配列にコピーします。
  2. OnBeforeSerialize()
    コールバックが完了すると、Unityはアレイをシリアライズします。
  3. その後、オブジェクトがデシリアライズされると、Unity は
    OnAfterDeserialize()
    コールバックを実行します。このコールバックバックでは、データをメモリ内のオブジェクトにとって都合の良い形式にTransformして戻すことができます。例えばキキー C# ディクショナリ を再作成します。

例 1: Unity のデフォルトシリアル化がパフォーマンスの問題を引き起こす

樹木データ構造体があるとします。Unity にデータ構造体を直接シリアライズさせると、 null をサポートしない" という制限により、ストリームに大きくなり、多くのシステムでパフォーマンスが低下します。
using UnityEngine;using System.Collections.Generic;using System;public class VerySlowBehaviourDoNotDoThis :MonoBehaviour { Serializable public class Node { public string interestingValue = "value"; //The field below is what makes the serialization data become huge because //it introduces a 'class cycle'. public List<Node> children = new List<Node>(); } //this gets serialized public Node root = new Node(); void OnGUI() { Display (root); } void Display(Node node) { GUILayout.Label ("Value: "); node.interestingValue = GUILayout.TextField(node.interestingValue, GUILayout.Width(200)); GUILayout.BeginHorizontal (); GUILayout.Space (20); GUILayout.BeginVertical (); foreach (var child in node.children) { Display (child); } if (GUILayout.Button ("Add child")) { node.children.Add (new Node ()); } GUILayout.EndVertical (); GUILayout.EndHorizontal (); }}

例 2: カスタムシリアル化によりパフォーマンスの問題を回避

この場合、樹木を直接シリアライズしないように Unity に指示し、樹木を Unity のシリアライザーに適したシリアライズ形式で格納するための別のフィールドを作成します。
using System.Collections.Generic;using System;public class BehaviourWithTree :MonoBehaviour, ISerializationCallbackReceiver { // Node class that is used at runtime. // This is internal to the BehaviourWithTree class and is not serialized. public class Node { public string interestingValue = "value"; public List<Node> children = new List<Node>(); } // Node class that we will use for serialization. Serializable public struct SerializableNode { public string interestingValue; public int childCount; public int indexOfFirstChild; } // The root node used for runtime tree representation.シリアライズされていません。 Node root = new Node(); // This is the field we give Unity to serialize. public List<SerializableNode> serializedNodes; public void OnBeforeSerialize() { // Unity is about to read the serializedNodes field's contents. // The correct data must now be written into that field "just in time". if (serializedNodes == null) serializedNodes = new List<SerializableNode>(); if (root == null) root = new Node (); serializedNodes.Clear(); AddNodeToSerializedNodes(root); // Now Unity is free to serialize this field, and we should get back the expected // data when it is deserialized later. } void AddNodeToSerializedNodes(Node n) { var serializedNode = new SerializableNode () { interestingValue = n.interestingValue, childCount = n.children.Count, indexOfFirstChild = serializedNodes.Count+1 } serializedNodes.Add (serializedNode); foreach (var child in n.children) { AddNodeToSerializedNodes (child); } } public void OnAfterDeserialize() { //Unity has just written new data into the serializedNodes field. //let's populate our actual runtime data with those new values. if (serializedNodes.Count > 0) { ReadNodeFromSerializedNodes (0, out root); } else { root = new Node (); } int ReadNodeFromSerializedNodes(int インデックス、 out ノードノード) { var serializedNode = serializedNodes [index]; // Transfer the deserialized data into the internal Node class Node newNode = new Node() { interestingValue = serializedNode.interestingValue, 子 = 新しいリスト<Node> () } // The tree needs to be read in depth-first, since that's how we wrote it out. for (int i = 0; i != serializedNode.childCount; i++) { Node childNode; index = ReadNodeFromSerializedNodes (++index, out childNode); newNode.children.Add (childNode); } node = newNode; return index; } // This OnGUI draws out the node tree in the Game View, with buttons to add new nodes as children. void OnGUI() { if (root != null) { Display (root); } } void Display(Node node) { GUILayout.Label ("Value: "); // Allow modification of the node's "interesting value". node.interestingValue = GUILayout.TextField(node.interestingValue, GUILayout.Width(200)); GUILayout.BeginHorizontal (); GUILayout.Space (20); GUILayout.BeginVertical (); foreach (var child in node.children) { Display (child); } if (GUILayout.Button ("Add child")) { node.children.Add (new Node ()); } GUILayout.EndVertical (); GUILayout.EndHorizontal (); }}

追加リソース