- Home /
Text Not Being Displayed above Instantiated Prefabs
I have a timer being displayed above my enemy sprites that count down consistently. The trouble is it doesn't work with prefabs that are instantiated in runtime. If I drag the prefab into the scene before running, the timer will show up just fine but those spawned in by my spawner script display nothing.
This is on the enemy character object:
public float lifetime; public Text textField;
public string timeLeft; enemyTextScript myScript; public GameObject myTextMesh;
// Use this for initialization
void Start () {
myScript = gameObject.GetComponentInChildren(typeof(enemyTextScript)) as enemyTextScript;
}
// Update is called once per frame
void Update () {
lifetime -= Time.deltaTime;
timeLeft = lifetime.ToString ("F2");
textField = GetComponent<Text>();
timeLeft = lifetime.ToString ("F2");
myScript.report(timeLeft);
if (lifetime <= 0) {
Destroy (gameObject);
lifeTime.instance.lifetime += 2f;
}
}
void OnCollisionEnter2D(Collision2D col){
if (col.gameObject.tag == "pAttack") {
if (col.gameObject.name == "slash(Clone)") {
lifetime -= 3f;
}
if (col.gameObject.name == "shuriken(Clone)") {
lifetime -= 5f;
}
}
}
void reportTime(){
timeLeft = lifetime.ToString ("F2");
}
And this is on the text object, a child of the enemy (and part of a canvas)
public Text textField; public string timeL;
// Use this for initialization
void Start () {
textField = GetComponent<Text>();
}
// Update is called once per frame
void Update () {
textField = GetComponent<Text>();
textField.text = ("" + timeL);
}
public void report(string time){
textField.text = ("" + time);
}
Thank you for any help you can offer, it's much appreciated.
Update: I think it has something to do with the instantiated prefabs not being setActive. I tried adding a text mesh ins$$anonymous$$d of a canvas with text as I saw that canvases are challenging to alter the active status. I changed every instance of Text in the second script to Text$$anonymous$$esh but its having exactly the same effect.
Your answer
Follow this Question
Related Questions
Text very big for one frame 0 Answers
How do you Instantiate Text as Child of Canvas c# 1 Answer
cachedTextGenerator not working with instantiated canvas 1 Answer
Creating Buttons with a C# Script 1 Answer
Instantiate prefab text into Canvas 2 Answers