I’m trying to initiate a prefab which needs a link to my GUIText Object. I really dont know what to do…
I had my player as an Object in the Hierarchy but now I need to make a prefab of it, so this is where I left off before creating a prefab:
class .....
public GUIText speedDisplay;
void update(){
updateSpeed();
}
public void updateSpeed()
{
speedDisplay.text = "Speed: " + (int)speed+", "+(int)((speed/maxSpeed)*100)+"% of max";
}
You can’t create a prefab with a reference to something outside it’s own hierarchy. For example: if you have a scene like this:
And reference the GUI Text inside the Prefab, the reference isn’t saved because Unity cannot get the instance of that GUI Text in other scenes, for example. To make this work, GUI Text need to be inside the Prefab’s hierarchy, like this:
But! If your reference is intent to be dynamic, you could add a tag (let’s say named “tag”) to the GUI Text and find it with:
GameObject.FindGameObjectWithTag("tag")
Remember to cache it in Start() method if you use the object often because FindGameObjectWithTag is kinda heavy.
First off, I want to point out that GUIText is outdated. You should use Text Instead.
If theText is on an object that has a specific tag, you can do this:
using System.UI;
public Text exampletext;
void Start(){
exampletext = GameObject.FindGameObjectWithTag("taggoeshere").GetComponent<Text>();
}
GameObject.FindGameObjectWithTag gets the gameobject in the scene that has the tag you want, and then GetComponent() gets the component of the Text type from the GameObject.