Skip to content

Instantly share code, notes, and snippets.

@snlehton
Created December 19, 2017 12:08
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snlehton/27d2aa9591588fdacf75c8ab65bfb5f4 to your computer and use it in GitHub Desktop.
Save snlehton/27d2aa9591588fdacf75c8ab65bfb5f4 to your computer and use it in GitHub Desktop.
A simple Unity example script that makes a UI component track position of world space object rendered with specific world space camera. Canvas needs to be in Screen Space Camera mode.
// A simple Unity example script that makes a UI component track position of world space object rendered with
// specific world space camera. Canvas needs to be in Screen Space Camera mode.
[ExecuteInEditMode]
public class UIFollow : MonoBehaviour
{
[Tooltip("World space object to follow")]
public GameObject target;
[Tooltip("World space camera that renders the target")]
public Camera worldCamera;
[Tooltip("Canvas set in Screen Space Camera mode")]
public Canvas canvas;
private void LateUpdate()
{
var rt = GetComponent<RectTransform>();
RectTransform parent = (RectTransform)rt.parent;
var vp = worldCamera.WorldToViewportPoint(target.transform.position);
var sp = canvas.worldCamera.ViewportToScreenPoint(vp);
Vector3 worldPoint;
RectTransformUtility.ScreenPointToWorldPointInRectangle(parent, sp, canvas.worldCamera, out worldPoint);
rt.position = worldPoint;
}
}
@shahanbutt
Copy link

Can we do this the other way around? Like the world space object follow the UI object.

@sima995
Copy link

sima995 commented Dec 16, 2021

Awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment