LoginSignup
10
9

More than 5 years have passed since last update.

[C#]クラス名の文字列からインスタンス作ったり、メソッド呼んだり

Posted at

クラス名の文字列からインスタンス作ったり、メソッド呼んだり

リフレクションを利用します。

public class Character
{
    private Vector3 position;

    public Character()
    {
        this.position = Vector3.zero;
    }

    public virtual void Move()
    {
        this.position += Vector3.right * right * Time.deltaTime;
    }
}

public class Player : Character
{
}

public class Enemy : Character
{
}

void Main()
{
    string className = "Player";
    Type type = Type.GetType(className);

    // インスタンス作ったり
    Character character = (Character)Activator.CreateInstance(type);

    // メソッド呼んだり
    MethodInfo method = type.GetMethod("Move");
    method.Invoke(character);

    // 引数渡したい場合
    // Object[] args = { "A", "B", "C" };
    // method.Invoke("Hoge", args);
}
10
9
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
10
9