1

When I collect a power-up in my game I want to instantiate dynamic text (e.g. "Missile" or "Shield") at the power-up's location but my code doesn't work.

This is my function (I admit it 's a bit messy):

public Text upgradeTxtPrefab;

void ShowUpgradeTxt (string _upgradeTxt) {

        // find canvas
        GameObject canvas = GameObject.Find("Canvas");

        Text tempUpgradeTxt = (Text)Instantiate (upgradeTxtPrefab);

        tempUpgradeTxt.fontSize = 24;

        tempUpgradeTxt.transform.position = this.transform.position;

        tempUpgradeTxt.transform.SetParent (canvas.transform, false);

        upgradeTxtPrefab.text = _upgradeTxt;

}
halfer
  • 19,824
  • 17
  • 99
  • 186
drpelz
  • 811
  • 11
  • 43

1 Answers1

2

It looks like you are not setting the right text. You're setting the text for upgradeTxtPrefab but you instantiated tempUpgradeTxt

It should be tempUpgradeTxt.text = _upgradeTxt;

Dtb49
  • 1,211
  • 2
  • 19
  • 48
  • I changed it like you said but I still can't see the text. – drpelz May 14 '18 at 15:44
  • At runtime when the Text object is created, check and see if in the inspector, does the text field contain text? – Dtb49 May 14 '18 at 15:46
  • Ok. The text is there. There seems to be a problem with the position. In the inspector it says x = -563 and y = -906. They are not on the visible screen. How do I fix this? – drpelz May 14 '18 at 15:52
  • Maybe try setting the position equal to the canvas's position and see where it puts it? I would also remove the line where you are changing the prefab's position. – Dtb49 May 14 '18 at 16:01
  • I deleted the two code lines with the position and updated my code. The position is still weird and I don't know what causes it. – drpelz May 14 '18 at 16:10
  • Also, make sure your text field is big enough to hold your text. If your text is too big, it will not render it. – Dtb49 May 14 '18 at 16:12
  • It renders the text. I already checked this. When I enter 0 in both position-fields (x and y) I can see the text in the center of the screen. – drpelz May 14 '18 at 16:15