How do I know the name of an object in Unity?

The inspector shows a name at the top, but I don’t think i can use this to refer to the component because I can put spaces in there. Is this wrong? If not, I need to know how to refer to the name of the object I’m trying to get.

The object in question was created by going to Hierarchy > Create > 2d object > sprite.

What is the name of this object? I get that in any given script if I did

Sprite RedSprite = new Sprite(); I could refer to that sprite as “RedSprite”. How do I do this with with components I inserted as I said above? Also, I think there’s a different between objects and components in Unity, can someone explain the different to me? C# is an OOP so I would think that everything is an object (not sure why Unity would even attempt to re-use that word, but they it seems they did).

https://docs.unity3d.com/ScriptReference/Object-name.html

1 Like

It also sounds like you are looking for this.

Its not recommended to use often, because its fairly slow performance wise. But using it sparingly is okay.

Not really. Here are the definitions

  • System.Object: The top level class all reference types must inherit from. You generally don’t need to care about this class.
  • UnityEngine.Object: A class that all UnityEngine classes inherit from. You generally don’t need to care about this class.
  • Component: A class that all things which attach to a GameObject must inherit from.
  • MonoBehavour: A class that all user defined scripts which attach to a GameObject must inherit from.

And remember this is an inheritance chain.

System.Object → UnityEngine.Object → Component → MonoBehaviour → YourScriptGoesHere.

If this class is also attached to GameObject, then “name” field is set to the name of that GameObject.

Well how in the heck was I supposed to know that? Why don’t they put the label of the field name next to the field like all the rest of the fields?

Anyways, I’m curious, how did you find this info? I did many internet searches and that did not come up. It’d be nice to operate with a little more autonomy, you know?

You probably want to memorise the API for GameObject, Monobehaviour and Transform. They are important.

A quick Google search for ‘how do I find a GameObjects name via script’ should have given you this result.