- Home /
score system for destroying objects
how can i make a point system, so that when a Gameobject of a particular Tag is destroyed, the points go up??
Answer by straydogstrut · May 08, 2010 at 11:23 AM
Keeping score is simply a case of incrementing the value of a variable when the player does something that will earn them points. To show the score on screen you can use either a guiText or something like a guilabel:
// using a gui label var currentScore : int = 0;
function OnGUI () { GUI.Label (Rect (10, 10, 100, 20), currentScore); }
In the case of the guiText you would need to convert the value of the score (which is an integer) to a string, like so:
// convert the variable scoreNumber which is an integer to a string currentScore.ToString();
// set this to the text value of your guiText to display it guiText.text = currentScore;
To increment the value of the currentScore variable, you could use something like the following. This is a modified extract from the Unity Game Development Essentials book where the player collects batteries by walking over them:
static var currentScore : int = 0;
// A function specifically for detecting collisions with colliders
// that have had the Is Trigger flag set in the inspector
function OnTriggerEnter(collisionInfo : Collider){
// if the current gameObject of the collider stored in the collisionInfo
// variable has a tag of "battery" (ie, we have hit a battery)
if(collisionInfo.gameObject.tag == "battery"){
// Increment the global score variable declared in the by 1
// ++ is short hand for currentScore = currentScore + 1;
currentScore++;
// Play a sound to confirm we have picked up a battery
audio.PlayOneShot(batteryCollectSound);
// Remove this particular battery from the scene (the object whose collider we have hit)
Destroy(collisionInfo.gameObject);
}
}
Thank you very much! I keep forgetting to use .ToString()! But you re$$anonymous$$ded me and resolved my issue without me having to ask a question on here! Thanks a ton.
Answer by spinaljack · May 08, 2010 at 11:01 AM
The best way is to notify another GameObject that keeps track of the score i.e. the player or a control GO. Something like this:
function ApplyDamage(damage){
hp-=damage;
if(hp<0){
Control.SendMessage("AddPoints",200);
Destroy(gameObject);
}
}
these script gives me erros it says hp uknown idntifier and controll unkown identifier
you probably know this but. It says hp uknown idntifier and controll unkown identifier because you need to Define them
Answer by Peter G · May 08, 2010 at 11:04 AM
This page explains how to do scoring well. It is about the 4th item down.
To determined if points should be added, add points from the death of the enemy instead of the player. So the player attacks the enemy. The enemy calculates the damage and determines it should die. It calls the Die method.
function Die () {
MySingleton.Instance.Score += 5;
Destroy(gameObject);
}