Get name of script

Is it possible to get the name of the current script in string format?

I saw that by overriding the ToString method it automaticly returns the name. But is there another way to get the name, so that I dont have to write a ToString method in every script?

this.name

… nope, thats the current gameobjects name… hmmm

ToString() is a public function on every Component. You need it so that it understands that you want a string name back and not something else, like the Component.

this.GetType().ToString()

However, class name as a string is generally not something you should be using. What are you wanting to do with this?

2 Likes

It’s for a custom editor, I need to show the names of the scripts in a node structure.

1 Like

I love this thread :slight_smile: This is what I have:

Debug.Log (this.gameObject.GetComponent<MonoBehaviour>())

It Debugs:

Player (PlayerController)

The name of the current script in this example is PlayerController and the script is attached to the GameObject Player
Not sure if that is exactly what you wanted, but it was a fun exercise for me! :smile:

1 Like

Thanks! It is almost what I wanted :slight_smile: What I am trying to do is to print only the name of the script which in this case is the PlayerController. But having the name in the brackets, I can extract it.

1 Like

New around here? We encourage the use of code tags instead of font changes. Makes everything nice and consistent and readable.

One of your collueges even put up a sticky about it. :slight_smile:

1 Like

ty! fixed for best practice :slight_smile:

2 Likes

this.GetType().Name will be the fastest method. Alternatively you may use MonoScript.FromMonoBehaviour(this).Name. Slower, allocating and editor only. The first one will give you the name of the class the second the name of the file but both need to be the same in unity. Parsing the this.ToString() result is something you definitely should not do.

2 Likes