Search Unity

My score variable is not increasing when condition is met (objects collide)

Discussion in 'Getting Started' started by idost, May 7, 2019.

  1. idost

    idost

    Joined:
    Nov 10, 2018
    Posts:
    2
    I recently started using unity and I am trying to make a 2D game where symbols (square, cross, triangle or circle) are spawned and fly left towards the player and the player have to shoot projectiles of the same type.

    I got the basics working but now I am trying to add score which would increase by 1 every time player succesfully matches the enemy symbol (when the two objects collide). The score increases but only once and then stays the same for every collision after and I just cant figure out why it is no working.
    Every response will be apreciated.
    (Sorry for my english, migh have some mistakes)

    Snímek obrazovky (100).png Snímek obrazovky (101).png
    Code (CSharp):
    1. using UnityEngine.SceneManagement;
    2. using UnityEngine.UI;
    3.    
    4. public class Enemy : MonoBehaviour
    5. {
    6.     public float speed;
    7.     public Text scoreText;
    8.     private int myScore = 0;
    9.  
    10.     private void Start()
    11.     {
    12.         scoreText = GameObject.FindGameObjectWithTag("Score").GetComponent<Text>();
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         transform.Translate(Vector2.left * speed * Time.deltaTime);
    18.     }
    19.  
    20.     private void OnTriggerEnter2D(Collider2D other)
    21.     {
    22.         if (other.CompareTag("Cannon"))
    23.         {
    24.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    25.         }
    26.  
    27.         if (other.tag == gameObject.tag)
    28.         {
    29.             myScore += 1;
    30.             Debug.Log(myScore);
    31.             scoreText.text = myScore.ToString();
    32.             Destroy(other.gameObject);
    33.             Destroy(gameObject);
    34.         }
    35.         else
    36.         {
    37.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    38.         }
    39.     }
    40. }
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    On line 33 you are destroying the GameObject which you are using to track the score. You probably should track the score on some singleton object which you won't need to destroy instead of in the Enemy script.
     
  3. idost

    idost

    Joined:
    Nov 10, 2018
    Posts:
    2
    Thanks for help but I am pretty new on Unity and I cant figure out how i would track score without comparing tags of the objects. Instead I am now increasing score when enemy is spawned. It isnt perfect but it works fine.