Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

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:
    8,388
    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;