using UnityEngine; public class UIFollowObject : MonoBehaviour { public Transform targetObject; // 要跟随的物体 public RectTransform uiElement; // UI元素的RectTransform组件 private Camera mainCamera; // 主摄像机 private void Start() { mainCamera = Camera.main; // 获取主摄像机的引用 } private void Update() { // 将物体的位置转换为屏幕空间坐标 Vector3 screenPos = mainCamera.WorldToScreenPoint(targetObject.position); // 更新UI元素的位置 uiElement.anchoredPosition = new Vector2(screenPos.x, screenPos.y); // 计算物体与摄像机之间的距离 float distance = Vector3.Distance(targetObject.position, mainCamera.transform.position); // 根据距离设置UI元素的缩放 uiElement.localScale = Vector3.one * distance; } }