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

What is the equivalent ClassName.class and classObjet.getClass() as in Java?

Discussion in 'Scripting' started by ProperNovice, May 16, 2021.

  1. ProperNovice

    ProperNovice

    Joined:
    Nov 1, 2016
    Posts:
    15
    So I can use it like:

    Code (CSharp):
    1. classObject.getClass().Equals(ClassName.class)
    Thank you
     
  2. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
  3. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,357
    I don't know Java so well, but if I understand these properly, I think the C# equivalent of
    Code (csharp):
    1. classObject.getClass().Equals(ClassName.class)
    Would be

    Code (csharp):
    1.  classObject.GetType().Equals(typeof (ClassName));
     
    ProperNovice likes this.
  4. ProperNovice

    ProperNovice

    Joined:
    Nov 1, 2016
    Posts:
    15
    Thank you both. It was exactly what I was looking for.

    I have another question if I may:

    Code (CSharp):
    1. private class Animal
    2. private class Dog : Animal
    Code (CSharp):
    1. List<Type> list = new List<Type>();
    2. list.Add(typeof(Animal));
    Code (CSharp):
    1. Dog dog = new Dog();
    2. Debug.Log(dog.GetType().Equals(list[0]));
    3. Debug.Log(dog.GetType() == list[0]);
    I want to make a true statement when checking the dog object being child of the first type of the List.

    The two Debugs throw False.

    Code (CSharp):
    1. Debug.Log(dog is Animal);
    This one turns True. But I want to use it with the first type object from the List, like 'dog is list[0]' and it isn't working.

    How can this come?
     
  5. VolodymyrBS

    VolodymyrBS

    Joined:
    May 15, 2019
    Posts:
    150
    You could use Type.IsAssignableFrom. So Your code will look like this
    Code (CSharp):
    1. Dog dog = new Dog();
    2. Debug.Log(list[0].IsAssignableFrom(dog.GetType()));
     
    ProperNovice likes this.
  6. ProperNovice

    ProperNovice

    Joined:
    Nov 1, 2016
    Posts:
    15
    Yes Volodymyr, this works perfectly. Thank you