SamsonGame/Assets/Scripts/Game/UI/Components/AnchorToTarget.cs

65 lines
1.5 KiB
C#

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<RectTransform>();
}
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;
}
}
}