インスタンスした継承先の子クラスを抽象クラス型の変数に入れた状態でメンバ変数にアクセスすると抽象クラスの初期値を参照してしまいます

C#

using System.Collections;using System.Collections.Generic;using UnityEngine; public class Test : MonoBehaviour { public StateDataClass currentState; public AttackState attackState; private void Start() { attackState = new AttackState(); currentState = attackState; currentState.Method(this); }} public abstract class StateDataClass { public string hoge = "抽象ステート"; public bool piyo = false; public virtual void Method(Test test) { }} public class AttackState : StateDataClass { public string hoge = "攻撃ステート"; public bool piyo = true; public override void Method(Test test) { Debug.Log("hoge:" + hoge + "  piyo:" + piyo); Debug.Log("test.attackState.hoge:" + test.attackState.hoge+ "  test.attackState.piyo:" + test.attackState.piyo); Debug.Log("test.currentState.hoge:" + test.currentState.hoge + " test.currentState.piyo:" + test.currentState.piyo); }}

キャラクターのステートをクラスで管理するために、まず抽象クラスを作り、overrideしたメソッドと変数を持たせた継承先の子クラスAttackStateをTestキャラクター内でインスタンスしました。
TestキャラクターはcurrentStateという抽象クラス型の変数を持ち、この中にインスタンスした待機、攻撃、移動、といった子クラスを入れて状態遷移を行います。
しかしcurrentState経由でインスタンスした子クラスの変数にアクセスしたところ以下のように抽象クラスの変数が返ってきてしまいうまくいきません。

イメージ説明

currentState経由で継承先の子クラスのメンバ変数にアクセスするにはどのようにすればよいでしょうか?

コメントを投稿

0 コメント