- Home /
GUI text help with adding numbers
Hey, need a script that adds one to my GUI text when an object is destroyed. I cant get it to do that though here is what I have:
var Counter : int = 1;
function Update () {
if(Destroy (gameObject.tag == "ball")){
Counter++;
guiText.text : "Score: "+Counter;
}
}
Answer by justin35f · Feb 01, 2013 at 11:40 PM
I took a look at this, and the problem doesn't appear to be in the code you posted. Unfortunately it's hard to tell without seeing more of you code. I made a quick little snippet in C#, just to test. This works:
using UnityEngine;
using System.Collections;
public class guiTest : MonoBehaviour
{
private int counter = 0;
void Start()
{
}
void Update()
{
counter++;
}
void OnGUI()
{
int x = 10;
int y = 10;
int w = 100;
int h = 20;
GUI.Label(new Rect(x, y, w, h), "Score: " + counter);
}
}
Let me know if this helps or not.
Just to be clear, this is only to increment the variable. Obviously you would need to handle how/where the variable is incremented elsewhere. Again, hard to tell where without seeing more code.
Answer by aldonaletto · Feb 01, 2013 at 11:45 PM
Well, this script will not work, for sure! You must make each ball increment the counter when it's destroyed, which can be done in a script attached to the ball prefab. The easiest way to do that is to make Counter a static variable in the GUIText script:
static var counter: int = 0;
function Update () { // just show the score counter:
guiText.text = "Score: " + counter;
}
Supposing that the script above is called "BallCounter.js", the ball script can be something like this:
function OnDestroy(){
BallCounter.counter++;
}
Attach this small script to the ball prefab, so that every ball will increment the counter when it's destroyed (OnDestroy actually is called when the script is destroyed, but this will happen when its owner - the ball - dies).
Your answer
Follow this Question
Related Questions
GUI after pressed Destruction 2 Answers
how can i destroy a cube when i press a gui button??? 1 Answer
Destroy a game object after a few seconds of being triggered? 2 Answers
How To Make GUI Buttons Load/Quit 1 Answer
GuiTexture Width Change 1 Answer