【发布时间】:2021-05-16 00:49:16
【问题描述】:
这是层次结构的屏幕截图,我有一个立方体和一个立方体的球体子项。 然后我有一个设置为空间世界覆盖的画布和一个画布的 UI 文本子项。
我希望 UI 文本与 Sphere 一起移动。
当我运行游戏时,文本位于球体的中心,但只有球体向上移动,文本保持在同一位置。我还尝试了其他画布模式屏幕空间相机和世界空间,但文本没有随着球体移动。
此脚本附加到球体:
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 void Start()
{
myText.GetComponent<Text>().alignment = (TextAnchor)TextAlignment.Center;
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;
myText.GetComponent<RectTransform>().position += Vector3.up * speed * Time.deltaTime;
}
else
{
transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime);
myText.GetComponent<RectTransform>().position = Vector3.MoveTowards(myText.transform.position, exitPosition, speed * Time.deltaTime);
}
}
}
}
我还尝试将带有文本的 Canvas 移动为 Sphere 的子对象,但文本仍然没有移动。
【问题讨论】: