- Home /
How do I make a Javascript object linked to a GUI Text?
I want to do something very simple. I'm very new, and I wanted to start off by making a player variable that holds the attribute score. However, I'm even having trouble with that. I found that adding a component script to a GUI Text and adding a value to guiText.text is the way to change the text. Declaring the object is what I'm having trouble with. This is what I've been trying:
var player = {
score:0
};
and
var player = new Object();
player.score = 0;
but every time I try to do this, I get some kind of Unity error. Here is my full code. I'm getting the error "Unknown identifier: 'score'."
#pragma strict
var player = {
score:0
};
function Start () {
guiText.text = "ass";
}
function Update () {
guiText.text = player.score.ToString();
}
Since 'Player' appears to be a script on another object, you might want to start by reading the following:
Javascript GetComponent:
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
http://unitygems.com/script-interaction-tutorial-getcomponent-unityscript/
Answer by Eric5h5 · Oct 10, 2014 at 01:22 PM
Unity does not use Javascript. You can use C#, Unityscript, or Boo. The docs unfortunately call it "Javascript" but it is not; it's a custom language preferably called Unityscript and not compatible with web Javascript. It's class-based, not prototype-based. The syntax is very similar to ActionScript3.
Also, Update runs once per frame. You should only put code in Update when it really needs to change every frame. The score will not do that, so you should make a function that is only called when the score changes:
private var score : int;
function Start () {
score = 0;
UpdateScore (0);
}
function UpdateScore (addToScore : int) {
score += addToScore;
GetComponent(GUIText).text = score.ToString();
}
Make sure you don't get in the habit of using the component shortcuts like "guiText"; always use GetComponent instead, because of this. (The only exception is "transform", since all GameObjects always have a Transform component.)
Your answer
![](https://koobas.hobune.stream/wayback/20220613164806im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Move object to raycast point. 3 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Collision at which side? 1 Answer
Random instantiation at an object 1 Answer
Storing and using weapons and objects 0 Answers