Unity – Enemy Nametag

      Comments Off on Unity – Enemy Nametag

When dealing with positioning 3D objects a scenario can often come up where you need an attached object to always be positioned or rotated relative to another point, ignoring parts of the parents transform. Consider a scenario where you want to have GUI display on an enemy, such as for a nametag or an overlay on the enemy. The canvas needs to always be attached to and move with the enemy, but it should always be facing the player.

You could solve this by controlling the position and rotation of the canvas manually, but Unity’s hierarchy system offers a much simpler approach. Keeping the canvas position relative to the enemy is simple; making the canvas a child of the enemy will ensure that the relative position i.e. the distance from the enemy is constant based on how we position it in the editor. Please note that in the case of a canvas attached to an object in 3D space you’ll need to change it to use world space and scale it down to a smaller size (not changing the height and width, just the scale)

Add a simple text element on the canvas to act as our name tag and position it accordingly. Setup your camera to allow controlled movement using your preferred method (drop in a standard character controller or script or camera or whatever) and you’ll see the problem we’re trying to solve, that while the canvas is anchored to the enemy as expected, we need it to rotate in relation to the player. My preferred method to solve this problem is to create an intermediary game object to act as an invisible pivot that will have the canvas as a child and be scripted to always point at the player.

First add the game object as a child of the enemy, and move the canvas to be a child of the empty object. For this example the pivot will have a local transform of 0,0,0 so it’s aligned with the enemy. The canvas transform remains unchanged.

Now we need a script on the pivot to make the forward equal to the direction between the enemy and the player. In this example it’s simple since the “player” is just the main camera.

When you run the application you’ll see that the canvas is there and follows the player’s movements, but the text is backwards. Simply rotate the canvas 180 degrees on the Y axis so that it’s facing away from the enemy instead of towards it and you’ll have a simple nametag effect.