0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unityでキャラのステータスのクラスを関連付けて記憶する

0
Last updated at Posted at 2017-07-10

UnityのMonoBehaviourを継承したクラスでは、publicで各種変数を設定すれば、Inspectorから編集・保存できるので様々な初期状態や途中状態の保存に有効なのは基本的なお話。

でもこの変数には独自のクラスを設定できない。
例えば以下のような画面に表示するユニット(Unit)のステータスのクラスである基底クラスUnitDataを作って、ユニット個別に特化したクラスを作っている。

UnitData.cs
// 略
public abstract class UnitData
{
    public string UnitName { get; protected set; } 
    public string SpriteName { get; protected set; }
    // Ability
    public int Strength { get; protected set; }
    public int Constitution { get; protected set; }
    public int Intelligent { get; protected set; }
    public int Wisdom { get; protected set; }
    public int Quickness { get; protected set; }
    public int Precision { get; protected set; }
    public int Social { get; protected set; }
    // コンストラクタ
    public UnitData() {
        Init();
    }
    //
    public abstract void Init();
}
public class ElfsanUnitData : UnitData
{
    public override void Init() {
        UnitName = "elfsan";
        SpriteName = "elfsan";
        //
        Strength = 80;
        Constitution = 85;
        Intelligent = 120;
        Wisdom = 110;
        Quickness = 100;
        Precision = 100;
        Social = 100;
    }
}

これをUnitに関連付ける。
早い話が、UnitDataクラスのtypeをstringで取り出して記憶してしまおうというアプローチ。
UnitData -> string はGetTypeで。
string -> UnitData はActivator.CreateInstanceとType.GetTypeで。

Unit.cs
public class Unit : MonoBehaviour {
    public string UnitType;
    public UnitData UnitData { get; private set; } 
    //
    void Start () {
        // インスタンス化して初期化関数に入力する
        SetUnitData((UnitData)Activator.CreateInstance(Type.GetType(UnitType)));
    }
    //
    public void SetUnitData(UnitData data) {
        UnitData = data;
        UnitType = data.GetType().ToString();
        // もろもろ初期化処理
    }
}

これの長所は、EditorからSetUnitDataを呼んでもOKなところ。
つまり、ある状態に持っていくために外部から設定できるし、かつそれが記憶される。

なお、シリアライズするとか他の方法も考えられるが、今は実装がらくちんなこれでとりあえずOKってことで。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?