using System; using UnityEngine; namespace RND { [RequireComponent(typeof(RectTransform))] public class AnchorToTarget : MonoBehaviour { public enum UpdateMode { UPDATE, LATE_UPDATE, FIXED_UPDATE } [SerializeField] private UpdateMode _updateMode; [SerializeField] private Vector3 _anchorOffset; [SerializeField] private Vector3 _worldLocalOffset; private Transform _target; private RectTransform _rectTransform; private void Start() { _rectTransform = GetComponent(); } public void SetTarget(Transform target, bool needUpdate = true) { _target = target; if (needUpdate) UpdatePosition(); } private void Update() { if (_updateMode != UpdateMode.UPDATE) return; UpdatePosition(); } private void LateUpdate() { if (_updateMode != UpdateMode.LATE_UPDATE) return; UpdatePosition(); } private void FixedUpdate() { if (_updateMode != UpdateMode.FIXED_UPDATE) return; UpdatePosition(); } private void UpdatePosition() { if (_target == null) return; _rectTransform.anchoredPosition = UI.Canvas.WorldToCanvasPosition(_target.position + _target.rotation * _worldLocalOffset) + _anchorOffset; } } }