Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

UI Follow Scene Objects?

Discussion in 'UGUI & TextMesh Pro' started by NeilM0, Oct 27, 2015.

  1. NeilM0

    NeilM0

    Joined:
    Mar 31, 2009
    Posts:
    135
    How do I make a UI that follows an object (eg, a healthbar that always stays the same size no matter how far the object is from the camera?

    My current setup that isn't working:

    I have a Screen Space - Camera canvas set to "Scale with screen size" 1136 x 640 and the slider is set to Height (1).

    There is a cube in the scene.

    I have an image in the canvas with a script on it that moves its position every frame with the following code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class TrackObject : MonoBehaviour {
    5.     public GameObject Obj;
    6.  
    7.     public Camera mCamera;
    8.     private RectTransform rt;
    9.  
    10.     void Start ()
    11.     {
    12.         rt = GetComponent<RectTransform>();
    13.     }
    14.    
    15.     void Update ()
    16.     {
    17.         if (Obj != null)
    18.         {
    19.             Vector2 pos = RectTransformUtility.WorldToScreenPoint(mCamera, Obj.transform.position);
    20.             rt.position = pos;
    21.         }
    22.     }
    23. }
    But what I'm currently seeing is the UI element move at half the speed of the objects in the camera. What am I doing wrong?
     
  2. NeilM0

    NeilM0

    Joined:
    Mar 31, 2009
    Posts:
    135
    Figured it out. I have to run the screen point through RectTransformUtility.ScreenPointToLocalPointInRectangle() to get the proper local position of the UI element.
     
    Joeqovan and AnomalusUndrdog like this.