Search code examples
c#unity-game-enginegame-engine

Unity, Updating score without update method


I am trying to update the different scores under different conditions. Here, I have 2 options: blue_ball matches with blue_rectangle and blue_ball matches with red_rectangle. Each condition calls theirs own function in order to increase the points however. it works only one time. when I debug I see that "SCORE--RED: 10" and "SCORE--BLUE: 10" later it does not update like 10, 20, 30... its allways 10.

I am new in C#, therefore I don't have much experience on it. I will appreciate if you guys can show me a way to correct this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{

float scoreBlue = 0;
float scoreRed = 0;

public void BlueGain()
{       
    scoreBlue += 10;
    Debug.Log("SCORE--BLUE: " + scoreBlue);

}

public void RedGain()
{         
    scoreRed += 10;
    Debug.Log("SCORE--RED: " + scoreRed);

}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (gameObject.tag == "blue_ball" && collision.gameObject.tag =="blue_rectangle")
    {
        BlueGain();
    }
    else if (gameObject.tag == "blue" && collision.gameObject.tag == "red_blue_rectangle")
    {
        RedGain();
    }

    if (collision != null)
    {

        Destroy(gameObject); 
        Destroy(collision.gameObject); 
    }
}

}


Solution

  • This doesn't work because this script is attached to a bullet (which can be understood from the class name) and when it hits, it increments scores scoreBlue or scoreRed. But the problem is once there's a trigger and the collision is not null, the game object to which this script is attached is destroyed, and so are the updated scores.

    The solution is to update the scores in a script that is not destroyed when the collision happens. Create a script ScoreManager.cs and add the following code to it.

    public static class ScoreManager {
        public static float scoreBlue = 0;
        public static float scoreRed = 0;
    }
    

    Static class and fields are used to be accessible globally across the scene without requiring a reference to it.

    Remove the fields scoreBlue and scoreRed in your Bullet.cs script. While incrementing the score in your Bullet.cs, modify the code to this

    public void BlueGain()
    {       
        ScoreManager.scoreBlue += 10;
        Debug.Log("SCORE--BLUE: " + ScoreManager.scoreBlue);
    }
    
    public void RedGain()
    {         
        ScoreManager.scoreRed += 10;
        Debug.Log("SCORE--RED: " + ScoreManager.scoreRed);
    }