Search Unity

Score Count not working

Discussion in 'Scripting' started by kasana_94, Aug 3, 2015.

  1. kasana_94

    kasana_94

    Joined:
    Apr 13, 2014
    Posts:
    24
    Hello everyone,

    I am having a little issue with displaying the score on scree.
    When a game object is destroyed the player gets 10 points for each. The script I am currently using does not increment the score by 10 point. It only shows once and does not increment.
    Please help, I am stuck with this.

    Thanks in advance.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5.  
    6. public class Bricks : MonoBehaviour {
    7.  
    8.     private int count;
    9.     public Text countText;
    10.     // Use this for initialization
    11.     void Start () {
    12.    
    13.         count = 0;
    14.         SetCountText ();
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update () {
    19.    
    20.     }
    21.  
    22.     void OnCollisionEnter(Collision col){
    23.    
    24.         Destroy (gameObject);
    25.         count = count + 10;
    26.             SetCountText ();
    27.  
    28.        
    29.         }
    30.  
    31.    
    32.     void SetCountText (){
    33.  
    34.         countText.text = "Score :" + count.ToString ();
    35.     }
    36.    
    37.  
    38.         }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you are destroying this gameobject and all things attached to it, this script included.

    The score must be held and displayed on another gameobject that isn't destroyed (usually something like the GameManager script etc.). This script then tells that script "add some points" before destroying itself.
     
  3. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
    It looks like your count variable is on each brick.

    Each brick starts with count 0. Gets destroyed and sets the count to 10 and sets your score string to ten.

    You need a score variable that sits in another class and only has on instance.

    You could create a score manager class to handle this. In your brick On collision function call this manager class and increment the score there.