- Home /
How to Get TextMesh component from the Gameobject the script is attached to?
I have a gameObject with a script attached to it. This gameObject has text attached to it. I want to be able to access this text in the script. How would I do this.
Please dont tell me to use GameObject.Find because that defeats the purpose because I will attach this script to many prefabs that all have 3D Text's. So then I would need to make lots of scripts.
Answer by StephanK · Jul 15, 2010 at 07:12 PM
If you can't use GameObject.Find you will have to save a reference to the GameObject or the TextMesh component somewhere. You can do this either by using public variables in your script and assign them throug the editor or if you have lots of them you should have some sort of manager that has a list or array of TextMeshes.
I'm looking to make a game like Phage Wars. How would that game get access to all the texts when collided? Link: http://armorgames.com/play/2675/phage-wars
Answer by Poemind · Sep 24, 2012 at 03:45 PM
Do you mean that there is no way of accessing a TextMesh component if it is a child of another Object? Because I need to do this as well, and the concept of doing this innumerable times is kind of crazy.
Answer by McMinty · Feb 13, 2014 at 03:53 AM
well... it may be a little late coming, but I have been working with somthing similar and thought I would answer anyway. it kinda depends on weather you want to set the text when you clone the prefab or from within the prefab's script.
From the script that clones the prefab try somthing like this:
#pragma strict
var TextObject: Rigidbody;
var TCol : Color;
function Start () {
CloneTextObject ();
}
function CloneTextObject () {
var TextOut : Rigidbody = Instantiate(TextObject, transform.position, transform.rotation);
var TouT = TextOut.GetComponent(TextMesh);
TouT.color = TCol;
TouT.text = "YAY Text!";
}
in this script the 3d text object has a Rigidbody componant since i wanted the text to move (fall) when spawned.
from inside the object itself it would be simpler just to set the text in the editer for the mostpart but if you were trying to get it to play a dialog or somthing try this:
#pragma strict
var TCol : Color;
function Start () {
TextOut ();
}
function TextOut () {
var TouT = GetComponent(TextMesh);
TouT.color = TCol;
TouT.text = "YAY Text!";
}
and either way, don't forget to set the color in the inspector or leave out the color bits to leave it default.
hope this helps.