- Home /
script woe adding score
//My Code var playerScore : int = 0; var writing : GUIText;
function OnCollisionEnter(collision : Collision) { if(collision.gameObject){
Destroy(this.gameObject); playerScore++;
writing.text = "Score: " + playerScore;
} }
Answer by Kleptomaniac · Mar 11, 2013 at 05:35 AM
The problem is that when you run you OnCollisionEnter() function, you call Destroy(this.gameObject)
before you are even able to increment your score. This means it will not work as this script is attached as a component of your object instance and is destroyed along with your object. I would suggest either changing you execution order so that it increments before the Destroy() method call, or else controlling your score in another script altogether (I would go with the latter).
Hope that helps,
Klep
Changing the execution order did not work :( So I tried putting it in its own script. In the if statement it wont work, is there another way i could add score by destroying the enemy?
Code: var playerScore : int = 0; var writing : GUIText; var enemy : GameObject;
function Update() { if(Destroy.enemy) { playerScore+=100;
writing.text = "Score: " + playerScore; }
}
Ins$$anonymous$$d of putting this script on each individual enemy, why not put it on your player object? Like so:
private var playerScore : int = 0;
var writing : GUIText;
var enemy : GameObject;
function OnCollisionEnter (collision : Collision) {
if (collision.gameObject.CompareTag("Enemy") {
Destroy(collision.gameObject);
playerScore += 100;
writing.text = "Score: " + playerScore;
}
}
Simply tag your enemy "Enemy" and you're good to go. :)
$$anonymous$$lep
I followed your steps and unfortunately did not work. ;( I assigned the tag to the enemy and I also the writing as the gui text.
Did you get any errors or did nothing happen? I need more information in order to help you.
Edit: Also, I noticed an error in my script. You don't need the var enemy : GameObject
line. This still shouldn't cause it to not work though.