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.
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.