- Home /
Checki f Player is within area? C#
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
}}
Answer by aldonaletto · Sep 21, 2011 at 10:49 PM
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 } }
Thank you, but how would I tell Unity that I want the "OnTriggerEnter" to be linked with my cube?
It says in the post- OnTriggerEnter gets called if you set your collider to be a trigger! That's what happens when you set a collider to be a trigger.
This script must be assigned to the cube: when the trigger is entered, the scripts attached to the trigger object will have their OnTriggerxxx functions called.