Hello!
I have a few questions.
Below is code derived from an example someone gave me for putting a TextMeshPro text into the world in pure C#. I tried to whittle it down to the bare essentials so I could get a handle on it. It displays my text, but there are issues:
-
The position as set with rect is not consistent with world coordinates. The text appears close to the origin but the x value is 10, and the y value appears to have no effect (perhaps these are meant as “text” coordinates?) I understand this is an issue others have had, but I couldn’t find an answer. I would (LOVE) it if a change could be added to the code below so that I can set the position, rotation, and scale in a way that is consistent with other world objects.
-
There are several layers here. Maybe that’s necessary for displaying texts in the world, but it seems like a lot. Are all of these components really necessary?
As I said, this is derived from code that someone else gave me. I would like to make it as clear as possible and then share it as a solution because I think it might help other people who just want to display texts in world coordinates using only code.
Also, note that I do not need any other UI capabilities. I just need to be able to make a bunch of labels and to transform them using world coordinates.
Any suggestions would be greatly appreciated!
Here’s the code:
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
private RectTransform rect;
private float x;
void Start()
{
x = 10.0f;
GameObject canvasObject = new GameObject("UICanvas");
Canvas canvas = canvasObject.AddComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
canvas.worldCamera = Camera.main;
canvasObject.AddComponent<CanvasScaler>();
RectTransform panel;
panel = new GameObject("Panel").AddComponent<RectTransform>();
panel.transform.SetParent( canvasObject.transform );
panel.AddComponent<CanvasRenderer>();
GameObject newGameObject = new GameObject();
rect = newGameObject.AddComponent<RectTransform>();
rect.position = new Vector3( 10.0f, -1.3f, 0.1f );
newGameObject.transform.SetParent( panel );
TextMeshPro theText = newGameObject.AddComponent<TextMeshPro>();
theText.text = "Test";
theText.fontSize = 0.2f;
}
void Update()
{
x += 0.0001f;
rect.position = new Vector3( x, -1.3f, 0.1f );
//rect.eulerAngles = new Vector3( x, 0.0f, 0.0f );
}
}