- Home /
The question is answered, right answer was accepted
Display text above prefabs in Unity 4.6
Hi, 'm new to unity and stuck on a point. I want to display a timer as text above prefabs that are generated after random amount of time. I have made a Text object which is inside a Canvas. The problem is that text is displayed over the prefab which is on screen, but when another prefab is generated the text on the current prefab vanishes and moves on top of the new prefab. Following is the code. Thanks in advance people.
public class DestroyBomb : MonoBehaviour {
Text cntDownTimer;
private bool isGrounded = false;
public float timer = 5;
void Start()
{
cntDownTimer = GameObject.Find ("Text").GetComponent<Text>();
}
void Update ()
{
if (isGrounded)
{
timer -= Time.deltaTime;
cntDownTimer.rectTransform.position = new Vector3(transform.position.x + 2.15f, transform.position.y + 0.5f, 0f);
cntDownTimer.text = timer.ToString("0");
}
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.collider.gameObject.tag == "Ground")
isGrounded = true;
}
}
it's probably because you're searching for any object called "Text" and it will return the first one it finds.
if the Text
component is on the same object, then try
gameObject.GetComponent<Text>();
ins$$anonymous$$d... it wouldn't do any harm to add in some null
checks too.
hey thnx man....because of ur suggestion i got an idea....earlier text was a seperate object....now i made the text object as a child of my prefab....and now each prefab is getting its own overhead text....thnx a lot....the only thing i changed in the above code was the following....
void Start() {
cntDownTimer = gameObject.GetComponentInChildren (); }