LoginSignup
6
6

More than 3 years have passed since last update.

【Unity】ScriptableObjectではピュアクラスのポリモーフィズムが機能しない。でも...

Last updated at Posted at 2019-10-16

背景

RPGを開発していて、ActiveSkillにScriptableObjectを継承させマスタデータを管理しようとしました。

ActiveSkill自体をポリモーフィズムにするのではなく、スキル効果classとしてSkillExecutor
を設け、ActiveSkillのフィールドにSkillExecutorを持たせようとしました。

しかし、試しに動かしてみるとSkillExecutorのポリモーフィズムが効かない。

TwitterやSlackのUnity開発ギルドで教えていただいたのですが、どうやら現状(Unity2018.4)ではScriptableObjectでピュアクラスのポリモーフィズムが効かないことが判明しました。

コードのサンプル

using UnityEngine;
using System;

public class ActiveSkill : ScriptableObject {
    public SkillExecutor Executor;

    public void OnCreate (string typeName) {
        // スプレッドシートで型名を文字列で管理し、ScriptableObject.CreateInstanceした際に型名からインスタンス化させようとしている
        // なお直接 Executor = new PhysicExecutor(); としてもポリモーフィズムが働かないのは変わらない
        Type executorType =Type.GetType(typeName);
        Executor = (SkillExecutor)Activator.CreateInstance(executorType);
    }
}

[Serializable]
public class SkillExecutor {
    public void Execute () {
        Debug.Log("スキル効果だよ");
    }
}

[Serializable]
public class PhysicExecutor : SkillExecutor {
    public override Execute () {
        Debug.Log("物理ダメージ与えるよ");
    }
}

[Serializable]
public class MagicExecutor : SkillExecutor {
    public override Execute () {
        Debug.Log("魔法ダメージ与えるよ");
    }
}

しかし、なんとUnity2019.3ではこれができるようになるらしいです。
フィールドに[SerializeReference]を付ければOKらしい。

SerializeReference Attribute?

image.png

アップデート意欲が湧いてきました。
いざ人柱か...

追記

動作検証用のプロジェクトをGitHubリポジトリで公開しました。
azuma560/SerializeReferenceTest

6
6
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
6
6