Search Unity

Create a new class with string name

Discussion in 'Scripting' started by joss51, Aug 5, 2022.

  1. joss51

    joss51

    Joined:
    May 6, 2016
    Posts:
    18
    Hello,
    I have an abstract class and its derived classes.

    I create new derived class with:
    MyAbstractClass class1=new DerivedClass(parameter1, parameter2);

    It works well but I have to create them with the string name of the derived class.

    Something like this :
    MyAbstractClass Class1=new StringName(parameter1, parameter2);

    How can I do ?
    Thanks !
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    joss51 and Bunny83 like this.
  3. joss51

    joss51

    Joined:
    May 6, 2016
    Posts:
    18
    It works, thanks.
    Here is my code :

    Type t= Type.GetType(MyString);
    object[] parameters = new object[] { parameter1, parameter2 };
    var obj = t.Assembly.CreateInstance(MyString, false, BindingFlags.CreateInstance, null, parameters, null, null);
    MyAbstractClass Class1= (MyAbstractClass ) obj;