Hi
I’m having trouble making a working script. I need a script the will make the gui text, “X To Interact”, appear when I get near a certain game object, “Door”.
If it makes a difference I’m using the default unity first person controller
Hi
I’m having trouble making a working script. I need a script the will make the gui text, “X To Interact”, appear when I get near a certain game object, “Door”.
If it makes a difference I’m using the default unity first person controller
There are a couple of different ways of doing it.
Method 1. (Easiest, least desirable) You could just detect distance between the transform that represents the player and the transform that represents the door in an OnGUI function of the script, but unfortunately this will suck an awful lot of CPU time because most of the time, you are going to be nowhere near the door. It will also get worse as you add more doors to your game.
Method 2. (Preferred) You could put a collider on the door and have it detect when the player enters and leaves the collision box. When the collider is penetrated, enable a script that has an OnGUI function to display the text you want, and when the collider is exited, disable the script with the OnGUI function in it. This way the script that displays the text doesn’t execute when not in use.
Method 3. (Overkill, optimization for major level with hundreds or thousands of doors). You could cast a collision ray from the player forward along the axis of movement, to a depth of X meters, and if the ray intersects with a door, again, enable a script to display the desired text or spawn in an object that displays the message you need. This solution is really over-thinking the problem though until we are sure that the number of doors in your scene would become an issue using the collider in method 2.
I assume, of course, that you are going to be just displaying a piece of text with a simple OnGUI, rather than a fancier GUI library or a dynamic sprite that only shows up when in range. Either way, the principle remains the same.