0
\$\begingroup\$

I have GUI Labels over NPCs in my game, and the labels display their name above their head. But when I walk away and go somewhere else, their names stay on screen like it's mirrored or something?

Here's what I'm talking about:

This is how it looks normally

This is what it looks like on screen normally

This is what happens when I walk out of view.

This is what it looks like when I walk out of view

The Code:

using UnityEngine;
using System.Collections;

public class NPC : MonoBehaviour {

private float left;
private float top;
public float leftModifier;
public float topModifier;

private Vector3 NPCScreenPosition;

//FIX THE MIRRORING ISSUE

void Start () {

}

void Update () {
    Vector3 NPCNameWorldPosition = (transform.position + new Vector3(0.0f, transform.lossyScale.y, 0.0f));
    NPCScreenPosition = Camera.main.WorldToScreenPoint(NPCNameWorldPosition);
    left = NPCScreenPosition.x + leftModifier;
    top = Screen.height - (NPCScreenPosition.y + topModifier);
}

void OnGUI() {
    GUI.Label(new Rect(left, top, 150, 25), gameObject.name.ToString());
  }
}
\$\endgroup\$
  • \$\begingroup\$ If the character can't be seen by the camera, hide his character label? Also please don't add tags to the question title (eg. [Unity]) \$\endgroup\$ – bummzack Jul 24 '14 at 19:35
  • 1
    \$\begingroup\$ Not sure if this would work but try docs.unity3d.com/ScriptReference/Renderer-isVisible.html \$\endgroup\$ – Savlon Jul 24 '14 at 20:51
2
\$\begingroup\$

i recently resolved a similar issue by doing as bummzack suggested in his comment. the gui element is going to try and draw the nameplate on a 2d plane in front of the camera regardless of the direction its facing. you need to stop it manually

void Update () {

    Vector2 temp = cam.WorldToViewportPoint( target.position + offset );

    // check if camera is facing the target
    float angle = 60;  // my cameras view angle

    if ( Vector3.Angle( cam.transform.forward, transform.position - cam.transform.position) < angle ){

        transform.position = temp;
        guiText.text = "WORKING";
        guiText.color = Color.green;

    }

}
|improve this answer|||||
\$\endgroup\$
  • 2
    \$\begingroup\$ This will work. However using <some_renderer>.IsVisible seems like a simpler solution. Probably cheaper too. \$\endgroup\$ – Alex Jul 25 '14 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.