- Home /
How do you show a text when you are nearby an object?
I have an object just called "APPLE". I already have a hunger script. I just want a text that shows "Press 'E" to eat." when the player is near it.
Answer by fafase · Jan 04, 2014 at 10:42 AM
Add a collider polygon to your Apple object, a sphere is more appropriate. Then make it trigger and define a script like this:
public string message;
void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "Player")showGui = true;
}
void OnTriggerExit(Collider col)
{
if(col.gameObject.tag == "Player")showGui = false;
}
void OnGUI()
{
if(showGui)GUI.Box(new Rect(0,0,100,100),"Press E to eat the " + message);
}
void Update()
{
if(showGui && Input.GetKeyDown(KeyCode.E))
{
//Do some stuffs like health
Destroy(gameObject); //Remove the item
}
}
Good point of this, you have one script for any object since the message is defined in the inspector. You could even declare an enum to define what objects exist.
Simply, col is the other object colliding with. This script goes on the item, when colliding it may be the player or any other objects, you use col to check what it is. it is a reference to the colliding object.
Your answer
Follow this Question
Related Questions
Creating a text on a surface 1 Answer
4.6 Text Height/Lines 0 Answers
How to display text using javascript ? 1 Answer
TextField text component not updating 2 Answers