- Home /
How to display text using javascript ?
How am I supposed to display text when an object is triggered ? Example, I have an object and as soon as the player touches it, some text should be displayed. I have the following code:-
var mess="Petite";
function OnTrigggerEnter(other:Collider)
{
GUI.Label (Rect (10, 30, 1000, 20),"Word: " +mess);
}
Answer by KellyThomas · Dec 26, 2013 at 10:27 AM
`GUI` functions can only be called from `OnGUI()`.
So usually people will manage state in Update
or using triggers, then render according to state in OnGUI()
.
This script could be placed on an item in your level, and will display a message if the player (as identified by the tag system) is within it's trigger collider.
public var mess: String = "Petite";
private var inRange: boolean = false;
function OnTriggerEnter(other:Collider) {
if (other.tag == "Player") {
inRange = true;
}
}
function OnTriggerExit(other:Collider) {
if (other.tag == "Player") {
inRange = false;
}
}
function OnGUI() {
if(inRange) {
GUI.Label (Rect (10, 30, 1000, 20),"Word: " +mess);
}
}
Thanks, but it didn't work Nothing comes after I enter touch the object I have enabled "Is Trigger" I attached the script to the cube When I go through it, nothing is displayed
Sorry I had a typo: "OnTrigggerEnter" with 3 "G"s.
I have corrected the code in my answer and tested it in the application.
When I increase the text size, the text gets displayed twice.
Why is it so.
This is the code I used-:
var myStyle = new GUIStyle();
public var mess: String = "Petite";
private var inRange: boolean = false;
function OnTriggerEnter(other:Collider)
{
if (other.tag == "Player")
{
inRange = true;
}
}
function OnTriggerExit(other:Collider)
{
if (other.tag == "Player")
{
inRange = false;
}
}
function OnGUI()
{
if(inRange)
{
myStyle.fontSize=50;
GUI.Label (Rect (10, 30, 1000, 20),"Word: " +mess,myStyle);
}
}
And the text gets displayed like this-:
Is there any way to make it display only once
Please answer fast
@varunstorm now that you have the other question on GUI Text Formatting that is the appropriate place for this follow up question.
Please note that your images are appearing broken in both places so nobody can see what you are talking about.
Your answer
![](https://koobas.hobune.stream/wayback/20220613124858im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
GUIText only appearing in Unity Simlutor, but not actual iPad..why? 0 Answers
Create GUIText from Javascript 3 Answers
How do I display the contents of a class in a Label 0 Answers
changing font + size of text 1 Answer
Problem Displaying Score on GUI text 0 Answers