I want to have a cube in my world. When the player is near the cube, I want to display some text instructing the player what to do. The only way that I can seem to accomplish this is by:
void OnGUI()
{
if(GameObject.FindWithTag("Player").transform.position.x <= someAmountNearCube && GameObject.FindWithTag("Player").transform.position.x >= someAmount)
{
//Draw Text Here
}}
You have several ways to do that. You can check the distance from the cube and do whatever you want when the player is below certain distance, or you can create a cubic trigger and use the OnTriggerEnter to fire your message. Anyway, using FindWithTag (or other Find flavors) is by far the worse - it takes an appreciable amount of time to check all objects, thus you’d better to use any Find routine only at Start (the docs recommend this).
The cubic trigger has the better resolution, since it has the same shape as the cube, and is fast. Just change the cube collider dimensions to reach the range you want and set isTrigger to tell it’s a trigger, not a regular collider. You can then add a code like this to the cube script:
bool guiOn = false;
void OnTriggerEnter(Collider obj){ // turn message on when player is inside the trigger
if (obj.tag == "Player") guiOn = true;
}
void OnTriggerExit(Collider obj){ // turn message off when player left the trigger
if (obj.tag == "Player") guiOn = false;
}
void OnGUI(){
if (guiOn){ // only show message if guiOn is true
// draw text here
}
}