Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Creating new class object instance using only the class name

Discussion in 'Scripting' started by ProperNovice, Apr 21, 2021.

  1. ProperNovice

    ProperNovice

    Joined:
    Nov 1, 2016
    Posts:
    15
    Hello all,

    Let's say I have a class Number that doesn't inherit from MonoBehaviour. How do I create a new class object instance using only the class name?

    For example in Java we can use Reflection:

    Number.class.getConstructor().newInstance();

    How is something like this possible in C#?

    Thank you
     
  2. Sphinks

    Sphinks

    Joined:
    Apr 6, 2019
    Posts:
    267
    what´s the problem with just using new ?

    Code (CSharp):
    1. Number n = new Number();
    It´s the easiest way to create new objects.

    But using relfection is in C# possible too. Try this:
    Code (CSharp):
    1. Number instance = Activator.CreateInstance<Number>();
    If you wanna use reflection anstead of using "new" (whyever), you can have a look here as well:
    https://docs.microsoft.com/de-de/dotnet/api/system.reflection.assembly.createinstance?view=net-5.0
    https://docs.microsoft.com/de-de/dotnet/api/system.activator.createinstance?view=net-5.0
     
    Vryken and ProperNovice like this.
  3. ProperNovice

    ProperNovice

    Joined:
    Nov 1, 2016
    Posts:
    15
    Thank you Sphinks