3
\$\begingroup\$

I've got a 2D character sprite that I will move through a game board. I want to add over it, in a corner of the sprite, a Text object with the remaining HP of that character and also a health bar. I want those elements to move with the Character. Wherever the character moves, the UI follows.

I've tried adding a Text element in World Space and attaching it to the character sprite, but the Text is so huge that it's not displayed properly on top of it. I need to know how to adapt that text to the size of the sprite and how to make it follow it automatically. I guess that by setting the ch sprite as parent of the Text/canvas it would work, but I don't know how to get it working.

Thanks in advance

\$\endgroup\$
3
\$\begingroup\$
public Vector2 WorldToCanvasPoint(Vector3 a_position)
{
    Vector2 viewport = Camera.main.WorldToViewportPoint(a_position);
    return Vector2.right * (viewport.x - 0.5f) * m_canvasRect.width + Vector2.up * (viewport.y-0.5f) * m_canvasRect.height;
}

This is what you are looking for. Put this code on your Canvas, it could be called "CanvasManager" and should be a singleton. You can get m_canvasRect by doing:

this.GetComponentInParent<Canvas>().GetComponent<RectTransform>().rect;

Then you can create a "FollowTransform" script, with a

public Transform m_objectToFollow;

variable on it.

You put this script "FollowTransform" script on your HP Text, and add this:

public Transform m_objectToFollow;
private RectTransform m_rect;

void Start()
{
    m_rect = GetComponent<RectTransform>();

void Update()
{
    this.m_rect.anchoredPosition = CanvasManager.Instance.WorldToCanvasPoint(m_objectToFollow.position);
}

This way, the text will follow the transform you specified.

If you don't know how to create a singleton and what is it, you should search on google "Singleton design pattern". It's really useful and commonly used. Here's a way of doing it:

public class CanvasManager : MonoBehaviour {

    private static CanvasManager _instance;
    public static CanvasManager Instance { get { return _instance; } }

    void Start () {
        if (_instance != null && _instance != this)
        {
            Destroy (this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

You should read the Manual on World Space UI

For a health bar, the Slider component would be ideal. Your HealthBar component script would require a Slider, and Health component, make the canvas follow the transform, and set its value to the health of the object.

\$\endgroup\$

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.