Assigning Text to a prefab?

I have my tank prefab, and now I would like to assign the Text that I have in my canvas to that tank so that when the tank gets a powerup it tells the player.
I tried using

 MessageText = GameObject.Find ("PowerUpMessageCanvas").text;

but that didn’t seem to work. How should I go about this? And I understand you can’t just drag and drop the Text onto the prefab, because it won’t save when you click Apply.

First, the reason that isn’t working is because there’s no property of a GameObject called “.text”. You can use .GetComponent();

But wait, don’t leave yet! GameObject.Find is a crutch that you should avoid - there is never a situation where it’s the best solution. In cases like this - you have a prefab that needs to access a singular, ‘global’ type object, in this case your UI - a singleton is the best bet.

If you don’t have a centralized UI “master” script, make a new script, and add this:

public class SomeScriptName : MonoBehaviour {
public static SomeScriptName instance;
void Awake() {
instance = this;
}
public Text powerUpMessageCanvas;
}

Attach this script to the root of your UI, and link up the text in the inspector.

No more need for GameObject.Find - for that matter, no need to store the reference to the text object in your in-game object, either:

 //from anywhere else
SomeScriptName.instance.powerUpMessageCanvas.text = "foo";
2 Likes