This is a screenshot of the hierarchy I have a cube and a sphere child of the cube.
Then I have a canvas set to space world overlay and a UI text child of the canvas.
I want the UI text to move with the Sphere.
When I'm running the game the text is in the center of the sphere but only the sphere is moving up the text stay at the same position. I tried also the other canvas modes screen space camera and world space but the text is not moving with the sphere.
This script is attached to the 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);
}
}
}
}
I tried also to move the Canvas with the Text to be a child of the Sphere but still, the text is not moving.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…