How to make text appear when moving next to an object?

i am trying to make a script that makes text appear when you move next to an object. i have used the GUI text but i want it to appear when you move close to an object and dissapear when you move away from the object. is it possible to do this?

please help thanks.

Yes, that's possible. Here's what you do (assuming you are using JS). Create a sphere gameobject, and set it's collider to `trigger`. Remove the mesh renderer, and position it so that its trigger collider surrounds the gameObject. Next, put this script on it:

function OnTriggerEnter (other : Collider) {
    if (other.CompareTag ("Player")) {         
        SendMessageUpwards("SetTheGUI");
    }
}

function OnTriggerExit (other : Collider) {
    if (other.CompareTag ("Player")) {         
        SendMessageUpwards("UnSetGUI");
    }
}

Next, create another script, and put it on your main character:

var close = false;
var textFieldString = "text field";

function SetTheGUI () {
    close = true;
}

function UnSetGUI () {
    close = false;
}

function OnGUI () {
    if (close) {
        GUI.Label (Rect (25, 25, 100, 30), textFieldString);
    }
}

Now, if your player enters the trigger you made, it will set a boolean variable inside your player script to 'true'. If the value is true, then a GUI text field will appear. Hope this helps!


EDIT: If it's still not working, go over this list, making sure they are all right.

  1. Make sure your collider is surrounding the object - and make sure it's big enough.
  2. Is it set to be a trigger?
  3. Re-copy the code into two seperate files. Save them, and put the first on your trigger, and put the second on your player.
  4. Is your first player controller's tag set to "Player"?

ANOTHER EDIT: Set your trigger's code to this:

function OnTriggerEnter (other : Collider) {        
        SendMessageUpwards("SetTheGUI");
}

function OnTriggerExit (other : Collider) {        
        SendMessageUpwards("UnSetGUI");
}

Hmm. I really can't see anything else that's wrong in my instructions... It all should work. Try one more time, except replace the old trigger code with this above code. Also, recopy the player's code, I made a couple of changes.

Elbon96 did a fantastic job here.

Addition is that the Sphere Object needs to be a child of your main character's object, so that the "SendMessageUpwards()" can be received.

you need to creat a sphere collider (compomponent> physics> sphere collider. whn the object Selected) set it to “is trigger”. Then Attach this code to the player:

var displayMessage = false;

function OnTriggerEnter (other : Collider) {

displayMessage = true;
}

function OnGUI () {
if (displayMessage){
  GUI.Label (Rect (10, 10, 100, 20), "Hello World!");
  }
  }

*javascript

this code Does that any trigger you go to, It writes “hllow world” if you want its for Specific object I think you need to Write:

function OnTriggerEnter (other : Collider “object name”) {