- Home /
Score not properly updating when enemies are destroyed - javascript
My total points aren't adding up and my GUI isn't updating for some reason when I attempt to add points after an enemy is destroyed. How can I fix this? I should note that I am declaring variables early on in my code that set playerScore and totalScore as 0.
function OnTriggerEnter(collision:Collider) {
newSeed = Random.Range(1.0, 5.0);
if(gameObject.name == "Enemy_Pink(Clone)") {
if(collision.gameObject.tag == "Bullet") {
pinkLives--;
if(pinkLives == 0) {
applyPoints();
if(newSeed == 1) {
spawnAirTank(1);
}
Destroy(this.gameObject);
}
}
}
if(gameObject.name == "Enemy_Blue(Clone)") {
if(collision.gameObject.tag == "Bullet") {
blueLives--;
if(blueLives == 0) {
applyPoints();
if(newSeed == 2) {
spawnAirTank(2);
}
Destroy(this.gameObject);
}
}
}
if(gameObject.name == "Enemy_Red(Clone)") {
if(collision.gameObject.tag == "Bullet") {
redLives--;
if(redLives == 0) {
applyPoints();
redDead = true;
if(newSeed == 3) {
spawnAirTank(3);
}
Destroy(this.gameObject);
}
}
}
if(collision.gameObject.tag == "Bullet") {
Destroy(collision.gameObject);
}
if(collision.gameObject.tag == "Player") {
Destroy(collision.gameObject);
//Switch scene to gameOver
}
}
function OnGUI() {
GUI.Label(Rect(10,10,10,10), "Score: " + totalScore.ToString(), scoreStyle);
}
function applyPoints(){
if(gameObject.name == "Enemy_Pink(Clone)") {
playerScore+=10;
}
if(gameObject.name == "Enemy_Blue(Clone)") {
playerScore+=30;
}
if(gameObject.name == "Enemy_Red(Clone)") {
playerScore+=50;
}
totalScore+=playerScore;
Debug.Log("Player Score: " + totalScore);
}
My debugging shows the following:
So - obviously it is calling the proper script and should be adding/totaling the points, but it's not. I'm not sure how I can fix this.
what is issue with "playerScore" use ins$$anonymous$$d of using totalscore .. so no need to use "totalScore"
True, the way you are using += with playerScore negates the need for total score.
Answer by wibble82 · Mar 18, 2014 at 04:06 PM
Hmmm... assuming you're right about the debug log, everything else in your code looks fine.
I wonder, what happens if you move that debug.log into OnGUI - does it print out the new score every time?
And do you have any other objects in your game that have an OnGUI script, which may be drawing a different score bar that's confusing you?
-Chris
Well...there would be my issue...the score isn't registering to my OnGUI score box. I moved the debug there and it's not updating at all. And so far, nothing in my game other than this has OnGUI. So...I guess the issue now is that the score is updating, but not showing up OnGUI
Sorry, so to be clear, when you moved the debug output to OnGUI, what got printed out? Was it the correct data, or was it always 0? Or did you get no print outs at all?
Also, what exactly is the gui showing? Are you seeing Score: 0?
$$anonymous$$y apologies on the delayed response. The Debug is showing that the score isn't updating at all and the GUI score seems to not be updating either
Interesting, so (correct me if I'm wrong), but that means that when you log "totalScore" in applyPoints, it appears to be updated to the correct value. However when you log "totalScore" in OnGUI, it is always 0. That means 1 of 2 things:
they for some reason are looking at different variables. I'm no java script expert but perhaps you can define them in a way that causes this issue?
more likely is that you are resetting that total score somewhere else every frame! Try adding 1 to the totalScore every frame inside OnGUI. If something is resetting it then you'll only ever see the number 1 get logged. Otherwise you'll see it go up.
Search in your project for totalScore and see what you can find.
Looking at your script, I think I may see an issue.
It appears you are calling applyScore inside the OntriggerEnter function for your enemies, not the player:
if(gameObject.name == "Enemy_Pink(Clone)") { if(collision.gameObject.tag == "Bullet") { pinkLives--; if(pinkLives == 0) { applyPoints(); if(newSeed == 1) { spawnAirTank(1); } Destroy(this.gameObject); } } }
Here you say 'if I am a pink enemy, call applyPoints on this object, then destroy this object.
That would mean that every enemy/player with this script will be rendering a score of 0 to the screen. At times, an enemy will be awarded points, but they will be instantly destroyed so you won't see any difference.
Once all enemies are destroyed, you'll be left with just the player, who will never have been awarded points.
The proof of this will be to add to the debug log inside applyPoints Debug.Log(gameObject.name). I'll place a bet that you end up logging the name of your enemies, not the name of the player!
You need to flip that logic round in OnTriggerEnter so it is 'if collider.gameObject.name == "bla", do stuff then Destroy(collider.gameObject). And somehow get the player game object from somewhere, and award them points.
Answer by Dblfstr · Mar 19, 2014 at 03:55 PM
Create a variable previousScore. Then, in your applyPoints() funtion, set the variable previousScore to totalScore, then totalScore+=playerScore.
Now, in your OnGUI() function, check if totalScore>previousScore, if true, draw gui box. and set previous to total again.
function OnGUI(){
if(previousScore<totalScore){
GUI.Label(Rect(10,10,10,10), "Score: " + totalScore.ToString(), scoreStyle);
previousScore = totalScore;
}
else{
GUI.Label(Rect(10,10,10,10), "Score: " + totalScore.ToString(), scoreStyle);
}
}
function applyPoints(){
if(gameObject.name == "Enemy_Pink(Clone)") {
playerScore+=10;
}
if(gameObject.name == "Enemy_Blue(Clone)") {
playerScore+=30;
}
if(gameObject.name == "Enemy_Red(Clone)") {
playerScore+=50;
}
previousScore = totalScore;
totalScore+=playerScore;
Debug.Log("Player Score: " + totalScore);
}
The issue with this is that if I create previousScore in applyPoints() then OnGUI is stating that it can't find "previousScore" as an error. For some reason, my OnGUI is only calling Global variables and not responding to any changes that are being made to them in any other function. That's where I'm having trouble. Could this be a bug in Unity at this point? Because I'm not understanding why OnGUI isn't able to pick up a variable that is being changed.
In response to your comment, and the comment above regarding you comment. These variable should all be declared at the beginning of your script. I misspoke by saying create the variable in applyPoints(), more like set the variable, but declare and initialize it with your other variables, at the beginning.
Answer by SlyyGuyy · Mar 20, 2014 at 02:59 PM
Because my answer was most likely going to be too long to comment, here's the script for my Enemy_Controls. Hopefully with this, you're able to see the problem that may be happening in the game. Let me know if there are any questions.
#pragma strict
//Enemy shooting declarations
var enemyProjectile : GameObject;
var shootCoolDown : float;
var shootTimer : float; //Records how much time between shots
//Array declarations
var redEnemies = new Array();
var blueEnemies = new Array();
var redKill = new Array();
var blueKill = new Array();
//Check if enemies have been "killed"
var pinkDead = false;
var blueDead = false;
var redDead = false;
//Turn towards player declarations
var target : Transform;
var turnSpeed = 3;
var myTransform : Transform;
//Spawning Enemies & Air Tanks
var enemy : GameObject[];
var enemySpawned : boolean;
var airTank: GameObject[];
var seed : int;
var newSeed : int;
//Set how many lives each enemy has
var pinkLives = 1;
var blueLives = 2;
var redLives = 3;
//Scoring declarations
var playerScore : int = 0;
var totalScore : int = 0;
var previousScore : int = 0;
var scoreStyle : GUIStyle;
function Awake() {
myTransform = transform;
}
function Start () {
//target = GameObject.FindWithTag("Player").transform;
PlayerPrefs.SetInt("Score", playerScore);
InvokeRepeating("spawnEnemy",1,1);
}
function OnGUI() {
if(previousScore < totalScore) {
Debug.Log("Previoius Score < Total Score");
GUI.Label (Rect(10,10,10,10), "Score: " + totalScore.ToString(), scoreStyle);
previousScore = totalScore;
} else {
Debug.Log("Not true");
GUI.Label (Rect(10,10,10,10), "Score: " + totalScore.ToString(), scoreStyle);
}
//Debug.Log("Player Score: " + totalScore);
}
function Update () {
}
function OnTriggerEnter(collision:Collider) {
newSeed = Random.Range(1.0, 5.0);
if(gameObject.name == "Enemy_Pink(Clone)") {
if(collision.gameObject.tag == "Bullet") {
pinkLives--;
if(pinkLives == 0) {
applyPoints();
if(newSeed == 1) {
spawnAirTank(1);
}
Destroy(this.gameObject);
}
}
}
if(gameObject.name == "Enemy_Blue(Clone)") {
if(collision.gameObject.tag == "Bullet") {
blueLives--;
if(blueLives == 0) {
applyPoints();
if(newSeed == 2) {
spawnAirTank(2);
}
Destroy(this.gameObject);
}
}
}
if(gameObject.name == "Enemy_Red(Clone)") {
if(collision.gameObject.tag == "Bullet") {
redLives--;
if(redLives == 0) {
applyPoints();
redDead = true;
if(newSeed == 3) {
spawnAirTank(3);
}
Destroy(this.gameObject);
}
}
}
if(collision.gameObject.tag == "Bullet") {
Destroy(collision.gameObject);
}
if(collision.gameObject.tag == "Player") {
Destroy(collision.gameObject);
//Switch scene to gameOver
}
}
function applyPoints() {
if(gameObject.name == "Enemy_Pink(Clone)") {
Debug.Log("Pink Was Destroyed. Points Should Be Adding");
playerScore+=10;
}
if(gameObject.name == "Enemy_Blue(Clone)") {
Debug.Log("Blue Was Destroyed. Points Should Be Adding");
playerScore+=30;
}
if(gameObject.name == "Enemy_Red(Clone)") {
Debug.Log("Red Was Destroyed. Points Should Be Adding");
playerScore+=50;
}
previousScore = playerScore;
totalScore+=playerScore;
}
function spawnEnemy() {
var go : GameObject;
seed = Random.Range(1.0, 6.0);
target = GameObject.FindWithTag("Player").transform;
if (seed == 1)
{
go = Instantiate(enemy[0], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
go.AddComponent("Rigidbody");
go.rigidbody.useGravity = false;
go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), turnSpeed*Time.deltaTime);
//go.rigidbody.AddForce(go.transform.up * -(moveSpeed * Time.deltaTime));
go.rigidbody.AddForce(go.transform.up * -150);
}
if (seed == 2)
{
go = Instantiate(enemy[1], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
go.AddComponent("Rigidbody");
go.rigidbody.useGravity = false;
go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), turnSpeed*Time.deltaTime);
//go.rigidbody.AddForce(go.transform.up * -(moveSpeed * Time.deltaTime));
go.rigidbody.AddForce(go.transform.up * -150);
//blueEnemies.Add(go);
}
if (seed == 3)
{
go = Instantiate(enemy[2], Vector3(Random.Range(-4, 2), 14, 178), transform.rotation);
go.AddComponent("Rigidbody");
go.rigidbody.useGravity = false;
go.rigidbody.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), turnSpeed*Time.deltaTime);
//go.rigidbody.AddForce(go.transform.up * -(moveSpeed * Time.deltaTime));
go.rigidbody.AddForce(go.transform.up * -150);
//redEnemies.Add(go);
}
}
function spawnAirTank(chooseTank : int) {
var tank : GameObject;
var degrees : Vector3;
var time : float;
if(chooseTank == 0) {
tank = Instantiate(airTank[0], Vector3(5, 1, 178), transform.rotation);
tank.AddComponent("Rigidbody");
tank.rigidbody.useGravity = false;
var tankRotation = tank.transform.rotation;
var endRotation = tank.transform.rotation * Quaternion.Euler(degrees);
var rate = 1.0/time;
var t = 0.0;
while (t < 1.0) {
t += Time.deltaTime * rate;
tank.transform.rotation = Quaternion.Slerp(tankRotation, endRotation, t);
yield;
}
}
if(chooseTank == 1) {
tank = Instantiate(airTank[1], Vector3(5, 2, 178), transform.rotation);
tank.AddComponent("Rigidbody");
tank.rigidbody.useGravity = false;
var newTankRotation = tank.transform.rotation;
var finalRotation = tank.transform.rotation * Quaternion.Euler(degrees);
var newRate = 1.0/time;
var u = 0.0;
while (u < 1.0) {
u += Time.deltaTime * newRate;
tank.transform.rotation = Quaternion.Slerp(newTankRotation, finalRotation, u);
yield;
}
}
if(chooseTank == 2) {
tank = Instantiate(airTank[2], Vector3(5, 3, 178), transform.rotation);
tank.AddComponent("Rigidbody");
tank.rigidbody.useGravity = false;
var otherTankRotation = tank.transform.rotation;
var quitRotation = tank.transform.rotation * Quaternion.Euler(degrees);
var otherRate = 1.0/time;
var v = 0.0;
while (v < 1.0) {
v += Time.deltaTime * otherRate;
tank.transform.rotation = Quaternion.Slerp(otherTankRotation, quitRotation, v);
yield;
}
}
}
With the above code, what does the Debug.Log output? Also, in applyPoints()
previousScore = totalScore;
you could use Pastebin.com if you think your code will be too long for a post, that way things stay better organized in here.
Debug.Log comes up with "Not true" on every frame even after enemies are destroyed
Answer by Fappp · Mar 24, 2014 at 09:44 PM
The error must be in assigning the score variable. Where do you assign it and how?
Make sure it's assigned in the Start function!
Your answer
Follow this Question
Related Questions
Scoring System 1 Answer
how do i attach GUITEXT to a prefab 1 Answer
Have readout of score at certain increments (JavaScript) 1 Answer
Need help displaying score (JavaScript) 1 Answer
facebook with unity problem 0 Answers