@anon21877998 Here’s a code I put together for you. It works on my end. Attach it to any gameObject or the camera. Then from any script, all you need to create a text is :
UIManager.Instance.AddText("text","textid",fontSize,globalPosition, eulersAngles );
Also I added a little function so you can remove the text if you want but you will need the textid you used when you created it:
UIManager.Instance.RemoveText("textid");
I added a text demo, you can delete it if you like. I put DELETE
comments on it.
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
private RectTransform panel; // Reference to the RectTransform of the UI Panel.
public List<TMP_Text> textList; // List to store TMP_Text components.
public static UIManager Instance; // Singleton instance of the UIManager.
// Awake is used to initialize any variables or game state before the game starts.
private void Awake()
{
// Ensure only one instance of UIManager exists.
if (Instance == null)
Instance = this;
else
DestroyImmediate(this);
}
// Start is called before the first frame update.
void Start()
{
SetupUI();
}
// Sets up the UI components.
void SetupUI()
{
// Create a new Canvas object and add required components.
GameObject canvasObject = new GameObject("UICanvas");
Canvas canvas = canvasObject.AddComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
canvas.worldCamera = Camera.main;
canvasObject.AddComponent<CanvasScaler>();
canvasObject.AddComponent<GraphicRaycaster>();
// Add EventSystem for interaction, if it doesn't already exist.
if (GameObject.FindObjectOfType<EventSystem>().IsUnityNull())
canvasObject.AddComponent<EventSystem>();
canvasObject.AddComponent<StandaloneInputModule>();
// Create a Panel which will act as the parent for all text components.
panel = new GameObject("Panel").AddComponent<RectTransform>();
panel.transform.SetParent(canvasObject.transform);
panel.AddComponent<CanvasRenderer>();
// Initialize the list for text components.
textList = new List<TMP_Text>();
// DELETE - Test text spawning (this can be removed once testing is complete).
StartCoroutine(TextSpawner(20));
}
// DELETE - Test method to spawn random texts (intended for visualization and can be deleted after testing).
private IEnumerator TextSpawner(int spawnAmount)
{
int counter = 0;
List<string> texts = new List<string>()
{
"Hi there!",
"I am cool!",
"Weeeeeeeeee!",
"I love AI",
"Blah Blah",
};
while (counter < spawnAmount)
{
yield return new WaitForSeconds(1f);
// Generate random positions, rotations, and pick a random text.
int randomInt = UnityEngine.Random.Range(0, texts.Count);
float posX = UnityEngine.Random.Range(-10f, 20);
float posY = UnityEngine.Random.Range(-10f, 20);
float posZ = UnityEngine.Random.Range(1f, 60f);
float rotX = UnityEngine.Random.Range(-90f, 90f);
float rotY = UnityEngine.Random.Range(-90f, 90f);
float rotZ = UnityEngine.Random.Range(-90f, 90f);
Vector3 position = new Vector3(posX, posY, posZ);
Vector3 rotation = new Vector3(rotX, rotY, rotZ);
// Add the text to the UI.
AddText(texts[randomInt], $"id{counter}", 64, position, rotation);
counter++;
}
Debug.Log($"All {textList.Count} texts are on screen.");
while(counter > 0)
{
yield return new WaitForSeconds(1f);
counter--;
RemoveText($"id{counter}");
}
Debug.Log($"All texts have been removed from the screen.");
}
// Method to add a text to the UI with specified attributes.
public void AddText(string text, string textid, float fontSize, Vector3 position, Vector3 rotation)
{
// Create a new GameObject for the text and set its attributes.
GameObject newGameObject = new GameObject(textid);
RectTransform rect = newGameObject.AddComponent<RectTransform>();
rect.position = position;
rect.Rotate(rotation);
newGameObject.transform.SetParent(panel);
TextMeshPro newText = newGameObject.AddComponent<TextMeshPro>();
// Set specific TextMeshPro settings, extend this as you see fit.
newText.enableWordWrapping = false;
newText.text = text;
newText.fontSize = fontSize;
// Add the new text to our list.
textList.Add(newText);
}
// Method to remove the text from the UI based on its ID (name).
public void RemoveText(string textid)
{
TMP_Text textFound = null;
foreach (TMP_Text text in textList)
{
if (text.gameObject.name.Equals(textid))
{
textFound = text;
break;
}
}
// Check if we found the text and if so lets remove it from the list and destroy it.
if(textFound != null)
{
textList.Remove(textFound);
Destroy(textFound.gameObject);
}
else
{
Debug.Log($"Could not find textid: {textid}");
}
}
}