• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by SlyyGuyy · Mar 18, 2014 at 03:47 PM · javascriptscoreenemiesscoring

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:

alt text

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.

screen shot 2014-03-18 at 11.46.07 am.png (23.5 kB)
Comment

People who like this

0 Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Quokmoon · Mar 19, 2014 at 04:28 PM 0
Share

what is issue with "playerScore" use instead of using totalscore .. so no need to use "totalScore"

avatar image Dblfstr · Mar 19, 2014 at 05:47 PM 0
Share

True, the way you are using += with playerScore negates the need for total score.

4 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

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

Comment

People who like this

0 Show 18 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SlyyGuyy · Mar 18, 2014 at 04:10 PM 0
Share

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

avatar image wibble82 · Mar 18, 2014 at 05:27 PM 0
Share

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?

avatar image SlyyGuyy · Mar 19, 2014 at 12:33 AM 0
Share

My 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

avatar image wibble82 · Mar 19, 2014 at 11:35 AM 0
Share

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.

avatar image wibble82 · Mar 20, 2014 at 03:22 PM 1
Share

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.

Show more comments
avatar image

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);
 }
Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SlyyGuyy · Mar 19, 2014 at 10:15 PM 0
Share

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.

avatar image Dblfstr · Mar 20, 2014 at 01:44 PM 0
Share

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.

avatar image

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;
         }
     }
 }
Comment

People who like this

0 Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Dblfstr · Mar 20, 2014 at 06:21 PM 0
Share

With the above code, what does the Debug.Log output? Also, in applyPoints()

 previousScore = totalScore;
avatar image stevethorne · Mar 20, 2014 at 06:26 PM 0
Share

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.

avatar image SlyyGuyy · Mar 20, 2014 at 08:26 PM 0
Share

Debug.Log comes up with "Not true" on every frame even after enemies are destroyed

avatar image

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!

Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Scoring System 1 Answer

Accessing Script From Other Script Causes Lag? 1 Answer

Scoring System Java 1 Answer

Score system problem 1 Answer

I need help making a score system for a First Person Controller 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges