'How add text above multiple objects?

I created a cube with canvas child in world space and the main camera and a child of the canvas for ui text.

Now i want to make this canvas and text prefab or some how to use it in multiple objects for example if i have 100 cubes and i want to add above each one a different text ?

I can duplicate the Cube many times but if i have many different objects cubes player spheres ? Is there a way to make some kind of prefab from the Canvas and the Text only and to add it by script as child to each object ?

Text Above



Solution 1:[1]

This is a working solution.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class MoveOnCurvedLines : MonoBehaviour
{
    public GameObject textAbovePrefab;
    private List<GameObject> curvedLinePoints = new List<GameObject>();

    void Start()
    {
        curvedLinePoints = GameObject.FindGameObjectsWithTag("Curved Line Point").ToList();

        for(int i = 0; i < curvedLinePoints.Count; i++)
        {
            GameObject textAbove = Instantiate(textAbovePrefab);
            textAbove.transform.parent = curvedLinePoints[i].transform;
            RectTransform rectTransform = textAbove.GetComponent<RectTransform>();
            rectTransform.localPosition = new Vector3(0, 0, 0);
            rectTransform.sizeDelta = new Vector2(100, 100);
            rectTransform.localScale = new Vector3(0.1f, 0.1f, 0.1f);

            Canvas canvas = textAbove.GetComponent<Canvas>();
            canvas.renderMode = RenderMode.WorldSpace;
            canvas.worldCamera = Camera.main;

            foreach(Transform text in canvas.transform)
            {
                text.localPosition = new Vector3(0, 7, 0);
                text.GetComponent<Text>().text = i.ToString();
            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1741587