ScriptableObject
値の複製をさけることでメモリ消費を節約する為のクラス。(プレハブ自体に値を持たせるとInstantiate毎にメモリが確保される。)
RPGにおけるアイテムや敵のステータスのようなゲーム全体で共通な値を種類ごとに変更可能なデータテーブルとして定義することができる。
ScriptableObjectの作成
- MonoBehaviourの代わりにScriptableObjectクラスを継承する。
- [CreateAssetMenu]のAttributeを付ける。
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu] public class StatusTable : ScriptableObject { //サンプルデータ [SerializeField] int hp, attack, defense; public int Hp { get { return hp; } } public int Attack { get { return attack; } } public int Defense { get { return defense; } } }
ScriptableObjectのデータテーブルを生成
Asset>Create>”生成したいScriptObject”でデータテーブルを生成可能。
Inspectorビューで値の設定を行って完了。
参考
Unity : 不変データはScriptableObject を使って管理するとドヤ顔できるかもしれない(2016-06-25)
備考
Sceneが遷移してもデータが変わらないため、一時的なデータ保存に使えそう。
生成した共通のScriptObjectはList<T>とか配列に突っ込めば管理しやすそう。
グローバル変数の管理にも使えそう。