- Home /
Score not adding?
when i run into an object that adds to our score in my game it disappears like it's supposed to ,but my score just stays at 0. Could someone please help me?
My Scoring Script:
var score = 0;
print("Score: "+score);
function OnTriggerEnter( hit : Collider ) {
if(hit.Object.tag == "player") { score += 5; Destroy(gameObject);
Answer by skovacs1 · Aug 25, 2010 at 03:02 PM
What your script is doing:
//Declare a score variable within this script var score = 0; //Print the "Score: 0" as the score variable was just created and set to 0 print("Score: "+score);
//When someone enters the trigger volume function OnTriggerEnter( hit : Collider ) { //If the .Object of the collider (shouldn't this be .gameObject?) is tagged "player" if(hit.Object.tag == "player") { //Add 5 to the score variable local to this script score += 5; //Destroy the gameObject to which this script is attached Destroy(gameObject); } }
Like PixelMaster said, if you declared score to be static, that means that all instances of your script will share the same score variable, which will make it so that the score will increase when the player enters the volume of any of the objects to which this script is attached.
However, like AliAzin said, you should store your score in a separate script which you then access so that objects with different scripts can still access your score.
If you are going by your print statements according to the code above, then they will be wrong because they don't print the score after it has been changed.
What you probably want:
foo.js attached to another gameObject tagged "bar"
var score : int = 0;
function Start() { print("Score: "+score); }
//So that you can print your score, etc. function AddScore(amount : int) { score += amount; print("Score: "+score); }
your script attached to your triggers
var scoreManager: Component = GameObject.FindWithTag("bar").GetComponent("foo");
function OnTriggerEnter(){ scoreManager.AddScore(5); Destroy(gameObject); }
Answer by AliAzin · Aug 13, 2010 at 02:10 PM
because score is a local variable of each object. If you want to add score you should have a score manager object and each time add the score to it. like this:
var scoreManager : GameObjecy;
function OnTriggerEnter(){ scoreManager.GetComponent("yourManagerScriptName").score += 5;
}
Answer by pixelmixer · Aug 13, 2010 at 02:42 PM
You could also store the score as a Static variable so that the score persists even after the object is destroyed.
static var score = 0;
print("Score: "+score);
function OnTriggerEnter( hit : Collider ) { if(hit.Object.tag == "player") { score += 5; Destroy(gameObject);
If you go with then you will need to reset that static variable if you ever restart the current scene like the following: (In the same script file as your define the static variable)
function Awake() {
score = 0;
}
is there anything else special i can do or equip it to anything special, because it still doesn't work.