Hello, im creating a simple system, where if the player clicks on a gui button,
the player`s gem count goes down, however its not working…
The gem count script:
#pragma strict
var Gems : int = 0;
var healthGUI : GUIText;
function Start () {
}
function Update () {
OnGUI();
}
function OnGUI () {
healthGUI.text = "Gems " +Gems.ToString();
}
And this is the gui button script
var btnTexture : Texture;
function Start(){
GemsCount = GameObject.Find("Camera").GetComponent(GemsCount);
}
function OnGUI() {
if (!btnTexture) {
Debug.LogError("Please assign a texture on the inspector");
return;
}
if (GUI.Button(Rect(150,300,250,50)," ",""))
GemsCount.Gems++;
}
However i get this error: Expression GemsCount
cannot be assigned to.
can anybody help?
The problem is that you did not set up the variable at the beginning of the second script. The correct code should be something like this:
var btnTexture : Texture;
var gemCount : GemsCount;
function Start(){
gemCount = GameObject.Find("Camera").GetComponent(GemsCount);
}
function OnGUI() {
if (!btnTexture) {
Debug.LogError("Please assign a texture on the inspector");
return;
}
if (GUI.Button(Rect(150,300,250,50)," ",""))
gemCount.Gems++;
}
You probably need to take a differnet name for GemsCount as it matches with the class name. Try “gemsCount”.
Secondly, OnGUI() is called every frame by the engine, so theres no need to call it in the Update function.
Thirdly, I remind me that a GUIText only needs to be redefined on a change, means call
gemsCount.healthGUI.text = "Gems: " + gemsCount.Gems;
after adding the additional gem in the button script.
PS: Please note I’m not familar with JS but with C#, should probably work either way! 