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

Question How to get Class name of object?

Discussion in 'Scripting' started by Rachan, Jul 1, 2023.

  1. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    654
    Hi there!

    I really want to know how to get a class name of object

    I tried to use..
    Object MyObject= AssetDatabase.LoadAssetAtPath<Object>("script path");

    to load a script asset to an Object, and then I use
    MyObject.GetType().Name

    I really want to see, what a class of that script,
    But, I got "MonoScript"
    and this is not a class name of that file

    e.g. if
    public class TestScript{

    }

    actually, it must return "TestScript" Not "MonoScript"

    anyone has any ideas?

    Thanks!!!
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Well you're getting MonoScript because that's what you're loading, a monoscript asset.

    Maybe read the docs on mono script: https://docs.unity3d.com/ScriptReference/MonoScript.html

    Remember your script files are just text assets. They don't actually represent instances of a class or similar.

    Maybe you should post what you're actually trying to do, rather than these questions that make me think you're going down the wrong path.

    Also use code tags mate.
     
    Rachan likes this.
  3. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,300
    Code (CSharp):
    1. Debug.Log(this.GetType().FullName);
    or
    Code (CSharp):
    1. Debug.Log(this.GetType().ToString());
    The name of your script, it is prefixed with the namespace if you have one

    Type.FullName Property (System) | Microsoft Learn

    yeah
     
    Last edited: Jul 1, 2023
    Rachan likes this.
  4. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    654
    Thanks everyone! I will try.
     
  5. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    nameof(SomeType) also works if you know the type at compile time.
     
  6. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    654
    Oh, I used to found text asset once,
    so the only way is, I have to use ReadAllLine to get all string
    and finding a "class" and after it must be a class name Right?
     
  7. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Dude, look at the first property in the docs for Monoscript.

    You're over-complicating things and missing the most obvious solutions.
     
    Ryiah, Rachan and Hikiko66 like this.