Search code examples
c#unity-game-enginetags

How to set tags on components of a GameObject in Unity UI?


I am trying to be able to identify which of several Collider2D instances I'm looking at from within a script. The basic idea is that I have a Sprite with three Collision2D components. Each of these is intended to detect and respond to collisions with different types of surfaces in the game. I have tagged these other surfaces sprites in the editor with their corresponding identifiers. Now I want to tag the Collider2d components on my player object. This is so that when I retrieve the Collider2D objects in my script, I can tell which Collider2D instance I'm looking at by way of the tag property. I can then make them interact with these surfaces differently.

The problem is that the unity editor seems to hide these values form me in the inspector. I can only ever assign a tag to an entity which exists in the Hierarchy list. If I add a component to the Hierarchy, then add some child component to said component (think adding a sprite, then adding a Box Collider 2D to that sprite), the inspector window does not expose the tags for the child item.

enter image description here

You can see in the picture above that I have selected Player from the Hierarchy list. In the inspector view you can see a couple of Box Collider 2D components which I've attached to the Player GameObject. You'll also note that there exists no way to modify the tag associated with the Box Collider 2D. The only thing I can change here is the tag associated with the Player GameObject.

I'm confused as to why this isn't available in the editor. It very clearly is from within an attached script. I can retrieve an instance of the Collider2D instance(s) from the player with GetComponents() and I can see they have a tag property however, I cannot modify the tag from within the UI. I would rather not have to use their positions relative to the Player object in a script to update the tag. This seems like a design time property I should be able to set. Is this possible?


Solution

  • If you look at the document, you will find that this tag property represents the tag of this game object. You need to create child game objects under the rigidbody, add colliders and set layer for each game object separately.