【问题标题】:How can I move a ui text up?如何向上移动 ui 文本?
【发布时间】: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 的子对象,但文本仍然没有移动。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您需要将 Canvas 设置为 World Space,然后将 Canvas 设置为您的球体。

    另一种选择是将脚本添加到您的 UI 对象,并将其转换为世界空间坐标以跟随球体。大致如下:

    uiObject.transform.position = YourMainCamera.WorldToScreenPoint(theSphere.transform.position);
    

    如果您使用第二个选项,请不要不要更改您的画布类型并且不要不要将该对象设置为子对象。它将根据相对于您正在使用的相机的世界位置更改对象的位置以显示在球体上。

    我还应该添加,使用这两种解决方案中的任何一种,删除您用于移动文本的所有其他代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2021-12-22
      • 2021-10-29
      • 1970-01-01
      • 2015-08-13
      • 2018-11-30
      相关资源
      最近更新 更多