YuminekoGame
6/27/2019 - 7:27 AM

WorldToRect Camera

using UnityEngine;

public class WorldUI : MonoBehaviour {
    [SerializeField] private Transform target;
    [SerializeField] private Canvas canvas;
    [SerializeField] private Vector3 offset;

    private RectTransform myRect, parentRect;

    // Start is called before the first frame update
    void Start () {
        myRect = GetComponent<RectTransform> ();
        parentRect = transform.parent.GetComponent<RectTransform> ();
    }

    // Update is called once per frame
    void Update () {
        var screenPos = RectTransformUtility.WorldToScreenPoint (canvas.worldCamera, target.position + offset);
        Vector2 pos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle (parentRect, screenPos, canvas.worldCamera, out pos);
        myRect.localPosition = pos;
    }
}