How to get character to say description on key press

Hey everyone!

I’m trying to script a trigger in Unity 2D so that the player presses the “E” key and the character says a description of what he’s looking at. I’ve created an empty game object, marked it as “is trigger” with a box collider, everything is set, but I want it so that the description text is typed out next to his head. I’ve created a mock up of what I’m going for here:

38909-hello_door.gif

Below is the script that’s attached to the trigger.

using UnityEngine;
using System.Collections;

public class description2 : MonoBehaviour {

	string message = "";
	
	void OnTriggerStay2D(Collider2D collider) {
		if (collider.gameObject.tag == "Tajai") {
						if (Input.GetButtonDown ("Action")) {
								message = "This is the description text";
						}
				}
			if (collider.gameObject.tag == "Tajai") {
				if (Input.GetButtonUp ("Action")) {
				message = "";
			}
		}		
	}
	void OnGUI()
	{
		GUI.Label(new Rect(550, 300, 200, 20), message);
	}
	
}

I’m using this code for now because it was the only way to get the text to appear on screen. Before I was using a trigger that prompted the activation of a GUIText that was attached to the object to be clicked on for a description:

using UnityEngine;
using System.Collections;

public class description : MonoBehaviour {

		void OnTriggerStay2D(Collider2D collider) {
		if (collider.gameObject.tag == "Tajai") {
			if (Input.GetButtonDown ("Action")) {
				guiText.enabled = true;
			}
			if (Input.GetButtonUp ("Action")) {
				guiText.enabled = false;
		}
	}		
}

}

But all that did was activate and deactivate the GUIText gameobject in the inspector, but no text shows up.

I’ve been trying all kinds of methods but I’m not getting the effect I need. I would just like a fixed GUIText to the character that’s activated on key press to give a description of what he’s looking at. I found that I have to script animated text to get the effect like in my mock up gif I posted here.

Any help is much appreciated!

There is no reference to guiText in your script. Add this field above your OnTriggerStay2D method:

public GameObject guiText;

In the editor, click on your object, and drag-n-drop the gui text object from the hierarchy onto the field.
I never use GuiText in my scene, I aways do it with the GUI class, so you should do that. GUI.Label actually draws the text, and needs to be inside a new method in your class:

void OnGUI() {

 GUI.Label(new Rect(550, 300, 200, 20), message);

}

Hope this helps a bit!

  • Romejanic