How to compare 2 scores from 2 different Texts (GameObject)

Hi everyone, I am new to Unity and I trying to build a Space Invader 2 players. Each player gets their own score buy destroying aliens. The score are display in 2 different GameObjects Text. The player with the higher score when all aliens are destroyed wins. I am currently stuck with the part where I need to compare both score.

I am trying to play with this script but can’t make it works. Is anyone can help me please?
Thank you in advance.

  • public void GameOver()
  • {
  • if (player1.score > player2.score)
  • {
  • Debug.Log(“Player 1 won.”);
  • }
  • else if (player2.score > player1.score)
  • {
  • Debug.Log(“Player 2 won.”);
  • }
  • else
  • {
  • Debug.Log(“It’s Draw.”);

Well…what’s the issue? From the looks of things, you have two variables player1 and player2 each with a variable score and it’s just comparing them. Nothing wrong with the bit of code you showed.

I’m assuming score is an int variable, but with what little you showed, can’t see anything wrong.

1 Like

Thank you for your message. I am still trying to figure this out. This is how it is presented in the inspector.

Unfortunately, that doesn’t help. Those are UI Text objects, but you should have scripts. For example, post the script that contains the code you posted above. And post the script that is player1. And use code tags! Using code tags properly

1 Like

Well you probably mean something like this

float.Parse(GameObject.Find("Score").GetComponent<Text>().text) > float.Parse(GameObject.Find("Score2").GetComponent<Text>().text)

But this code is wrong, you should store score in some variable and use text component just for displaying.

1 Like

So, my score increase each time player shoot an alien. For each player’s bullet I have a script: bullet.cs for player 1 called spaceship and bullet2.cs for player 2 called spaceship2. Here are the 2 scripts, how can I compare their score when all aliens are dead, this is my issue.

This is the code for the bullet of player 1:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

// Needed to manipulate the UI
using UnityEngine.UI;

public class Bullet : MonoBehaviour
{

    public float speed = 30;

    private Rigidbody2D rigidBody;

    // Exploded alien Image
    public Sprite explodedAlienImage;

    // Use this for initialization
    void Start()
    {

        // Get reference to the ball Rigidbody
        rigidBody = GetComponent<Rigidbody2D>();

        // When the ball is created move it up
        // (0,1) at the desired speed
        rigidBody.velocity = Vector2.up * speed;

    }

    // Called every time a ball collides with something
    // the object it hit is passed as a parameter
    void OnTriggerEnter2D(Collider2D col)
    {
        // If Bullet hits a wall destroy bullet
        if (col.tag == "Wall")
        {
            Destroy(gameObject);
        }

        // If Bullet hits Alien destroy Alien and Bullet
        if (col.gameObject.tag == "Alien")
        {
            SoundManager.Instance.PlayOneShot(SoundManager.Instance.alienDies);

            // Increase the Score Text component
            increaseTextUIScore();

            // Change to exploded alien image
            // spriteRenderer.sprite = explodedAlienImage;
            col.GetComponent<SpriteRenderer>().sprite = explodedAlienImage;

            Destroy(gameObject);

            // Wait .5 seconds and then destroy Alien
            DestroyObject(col.gameObject, 0.5f);
                       
        }

        //David Test c# check for destroyed objects to load next scene   
        if (GameObject.FindWithTag("Alien") == null)
        {
            Debug.Log("yeah!");
            //SceneManager.LoadScene("Scene_GameOver");

        }

        // If Alien Bullet hits Shield destroy both
        if (col.tag == "Shield")
        {
            Destroy(gameObject);
            DestroyObject(col.gameObject);
        }

    }

    // Called when the Game Object isn't visible
    void OnBecameInvisible()
    {
        Destroy(gameObject);
    }

    // Increases the score the the text UI name passed
    void increaseTextUIScore()
    {
        // Find the Score UI component
        var textUIComp = GameObject.Find("Score").GetComponent<Text>();

        // Get the string stored in it and convert to an int
        int score = int.Parse(textUIComp.text);

        // Increment the score
        score += 10;

         // Convert the score to a string and update the UI
         textUIComp.text = score.ToString();
               
        }
    }

This is the code for the bullet of player 2:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

// Needed to manipulate the UI
using UnityEngine.UI;

public class Bullet2 : MonoBehaviour
{
    public float speed = 30;

    private Rigidbody2D rigidBody;

    // Exploded alien Image
    public Sprite explodedAlienImage;

    // Use this for initialization
    void Start()
    {

        // Get reference to the ball Rigidbody
        rigidBody = GetComponent<Rigidbody2D>();

        // When the ball is created move it up
        // (0,1) at the desired speed
        rigidBody.velocity = Vector2.up * speed;

    }

    // Called every time a ball collides with something
    // the object it hit is passed as a parameter
    void OnTriggerEnter2D(Collider2D col)
    {
        // If Bullet hits a wall destroy bullet
        if (col.tag == "Wall")
        {
            Destroy(gameObject);
        }

        // If Bullet hits Alien destroy Alien and Bullet
        if (col.gameObject.tag == "Alien")
        {
            SoundManager.Instance.PlayOneShot(SoundManager.Instance.alienDies);

            // Increase the Score Text component
            increaseTextUIScore();

            // Change to exploded alien image
            // spriteRenderer.sprite = explodedAlienImage;
            col.GetComponent<SpriteRenderer>().sprite = explodedAlienImage;

            Destroy(gameObject);

            // Wait .5 seconds and then destroy Alien
            DestroyObject(col.gameObject, 0.5f);

        }

        //David Test c# check for destroyed objects to load next scene   
        if (GameObject.FindWithTag("Alien") == null)
        {
            //SceneManager.LoadScene("Scene_GameOver");
                  
           
        }

        // If Alien Bullet hits Shield destroy both
        if (col.tag == "Shield")
        {
            Destroy(gameObject);
            DestroyObject(col.gameObject);
        }

    }

    // Called when the Game Object isn't visible
    void OnBecameInvisible()
    {
        Destroy(gameObject);
    }

    // Increases the score the the text UI name passed
    void increaseTextUIScore()
    {

        // Find the Score UI component
        var textUIComp = GameObject.Find("Score2").GetComponent<Text>();

        // Get the string stored in it and convert to an int
        int score2 = int.Parse(textUIComp.text);

        // Increment the score
        score2 += 10;

        // Convert the score to a string and update the UI
        textUIComp.text = score2.ToString();
    }

}

You are right, I just posted the scripts increasing the score. Thank you.

Well, there are issues here for sure. GameObject.Find is really not what you want to use. Honestly, a manager class would be better that has direct references to your text objects as well as maintaining int variables to track your scores.

As you have it now, you’re simply using the text and converting it, which isn’t the best way. If you had a manager script, you could call it when your game is over and then have it compare the two variables instead and display some results.

If you keep it the way it is, you’re going to have to have your gameover method find your text objects, convert them both into ints and then do the comparison on those two values. I just advise against this as it’s not the best design.

1 Like

Just for fun, I will add a little code, in case it helps at all :slight_smile:

Public Text score1;
Public Text score2;
int score1 = 0;
int score2 = 0;

// gaining score -- this could be either score1 or score2.
// They add the score, then adjust the text object that matches.
score1 += 10;
score1.text = score1.ToString();

// later, when comparing the winnner...   Very easy ;)
if(score1 == score2) {
   print("Tie game.");
   }
else if(score1 > score2) {
   // player1 won
  }
else {
  // player 2 won.
}

As mentioned, if you had this code done in a manager class, it could hold all of the references.
When you kill the aliens with your bullets, tell the manager class you have done this and it will take care of the details (scoring).

1 Like

I generally don’t use text components to store scores. Typically I store them as an int in whatever score tracking script I write for it, and set the score in the text component whenever it changes. Any score comparison is done with the int version.

1 Like
1 Like