How to add 3D text to the moving GameObject ?

I have a GameObject that is Instantiated at Runtime. Here I want to attach 3D Text to that Instantiated GameObject and that Text move along with the moving GameObject.

Here is my Code:

void Update()
    {
       GameObject gameObj = (GameObject)GameObject.Instantiate(myPrefab);
       GameObject _3d = (GameObject)GameObject.Find("txt");
       gameObj.transform.position = new Vector3(Random.Range(this.transform.position.x - 1, this.transform.position.x + 1), Random.Range(this.transform.position.y - 0.1f, this.transform.position.y + 0.1f), 0);
    
       // Here I tried to attach 3D Text

       // My Code is
       /*
           TextMesh t;
           t.transform.position = gameObj.transform.position;
           t = _3d.GetComponent<TextMesh>();
           //t = (TextMesh)_3d.GetComponent(typeof(TextMesh)); 
           t.text = "My New Text";
       */

    }

But this doesn’t add any Text to the gameObj. Help is needed.
Thanks in Advance.

The following code will add text to an game object. Before integrating it into your code, verify it works for you in a new scene:

  • Drag a font into Unity
  • Create an empty game object at the origin
  • Add the script below to the game object
  • Select the empty game object in the hierarchy
  • Drag the font you created in the first step onto the ‘font’ variable in the Inspector
  • Open up the font you added (click on the triangle). Reselect the empty game object and drag the material inside the font onto the ‘material’ variable in the Inspector.
  • Run the app to test

#pragma strict

var font : Font;
var material : Material;

function Update() {
	if (Input.GetKeyDown(KeyCode.A)) {
		gameObject.AddComponent(MeshRenderer);
		renderer.material = material;
		
		var tm = gameObject.AddComponent(TextMesh);
		
		tm.text = "Some text to display";
		tm.font = font;
		tm.characterSize = 0.25;
	}
}

It might be easier to create a TextMesh prefab and then Instantiate() prefab and make it a child of the moving game object.