- Home /
Link GUIText to a prefab?
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";
}
Is the GUIText object you are referencing into the prefab inside the prefab's hierarchy?
I dont really know what you mean but no it's not and I cant drag it in. Obviously. Isn't there a way to connect them with code?
Answer by kleber-swf · Oct 28, 2016 at 06:33 PM
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.
Answer by $$anonymous$$ · Oct 28, 2016 at 04:17 PM
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.
Your answer
Follow this Question
Related Questions
Script is reading from prefab instead of instance 1 Answer
Creating a weapon database from prefabs 1 Answer
Cant delete clones of prefab 1 Answer
How can i add all the prefabs in the assets directory and sub directories to List or Array ? 0 Answers
How to Instantiate prefab when dragging an object through a specific area? 1 Answer