- Home /
 
How to keep score?
Hello,
I just recently started Unity and am now starting to script with Javascript. I currently have this code so far that I found on here:
 function OnTriggerEnter(collisionInfo : Collider){
       Destroy (gameObject);
 }
 
               This destroys the object but I want to be able to show it in GUI Text on the top left. Does anyone know how to score the amount of objects you destroy/take?
Answer by FatWednesday · Sep 07, 2012 at 06:04 PM
you need an object somewhere that stores a variable (in this case an int would likely do). then just before your call to destroy() call a function on this object to increase or decrease the score appropriately. For example, place this script on an empty game object in your scene.
 public ScoreKeeper : MonoBehaviour
 {
      public static int Score;
      
      void Awake()
      {
           Score = 0;
      }
 
     void OnGUI()
     {
         GUI.Label(new Rect(0, 0, 100, 25), "Score: " + Score);
     }
 }
 
               Then since score is a static variable, you can just change it like this.
ScoreKeeper.Score++;
That code, by the way, is C#, not Javascript. It would be rewritten as:
static var score: int;
Awake () {
score = 0;
}
OnGUI() {
GUI.Label(new Rect(0, 0, 100, 25), "Score: " + score);
}
good point, sorry i hadn't even noticed the original was javascript. thanks for converting.
Your answer
 
             Follow this Question
Related Questions
Scoring (i'm stuck) 3 Answers
Basic Game Score Question. 1 Answer
How to make a saved score destroy on load new scene 0 Answers
Destroying gameobject 2 Answers
Most efficient way to get scores 1 Answer