Unity中如何让UI Text跟随移动的3D球体同步向上位移?
问题根因
你代码的核心问题是没有处理不同Canvas渲染模式下的坐标体系差异,Unity中Screen Space系列的Canvas的RectTransform坐标单位是屏幕像素,和3D世界空间的单位不互通,直接同步世界位移自然无法匹配。同时你之前将Canvas设为Sphere子物体但不生效,是因为没有调整World Space Canvas的默认缩放参数。
方案1:子物体挂载(无代码,最稳定)
无需写位置同步逻辑,修改层级和参数即可实现自动跟随:
- 把Canvas的渲染模式修改为World Space
- 将Canvas设置为Sphere的子物体
- 选中Canvas,在RectTransform组件中做如下设置:
- 位置(Position)设为(0, 0, 0)
- 旋转(Rotation)设为(0, 0, 0)
- 缩放(Scale)统一修改为(0.01, 0.01, 0.01)
- 调整Text的字体大小、尺寸到合适效果即可
注意:使用本方案请删除代码中所有对
myText位置赋值的逻辑,避免父物体跟随和代码控制冲突。
方案2:全局Canvas动态同步(适合多UI复用全局Canvas的场景)
不需要修改层级结构,直接替换原有代码中控制Text位置的逻辑即可,修改后的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Testing : MonoBehaviour { public GameObject myText; public float speed; public float offset; public bool go = false; private bool exited = false; private Vector3 exitPosition; private RectTransform textRt; private void Start() { myText.GetComponent<Text>().alignment = (TextAnchor)TextAlignment.Center; textRt = myText.GetComponent<RectTransform>(); Debug.Log("Position : " + transform.position); } private void OnTriggerExit(Collider other) { if (other.name == "Cube") { Debug.Log("Exited !"); } exitPosition = new Vector3(transform.position.x, transform.position.y + offset, transform.position.z); exited = true; } private void Update() { if (go) { // 处理球体移动逻辑 if (!exited) { transform.position += Vector3.up * speed * Time.deltaTime; } else { transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime); } // 同步Text位置:把3D世界坐标转成UI对应的屏幕坐标 Vector3 targetWorldPos = transform.position + Vector3.up * offset; Vector3 screenPos = Camera.main.WorldToScreenPoint(targetWorldPos); textRt.position = screenPos; } } }
这个方案适配所有Canvas渲染模式,不需要调整层级,通过坐标转换直接把3D世界位置映射到UI的屏幕位置。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

