Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying score in another scene on Unity

Tags:

c#

unity3d

In the game I am creating a 'Game Over' scene which loads once the player loses the game. During the game, the score is counted by the player's position on the screen and increases as the player's y-axis position increases.

I used this code to display the score on the scene the game was actually played:

using UnityEngine;
using UnityEngine.UI;

public class PlayerScore : MonoBehaviour 
{

    public Transform player;
    public Text scoreText; 

    // Update is called once per frame
    void Update() 
    {
        scoreText.text = player.position.y.ToString("0"); 
    }
}

I tried to use the same coding to display the final score of the player on the 'Game Over' screen. The problem I faced was that I was not able to identify the player on the 'Game Over' scene as the player was not an object or sprite on that scene.

Is there an easy way to reference the player sprite from the previous scene into the final ('Game Over') scene so I can use it to determine the final score?

This is the script I tried with a game object of the 'EndScene' within the playing scene:

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

public class EndMenu: MonoBehaviour 
{

    public Text scoreText;
    public Transform player;
    public static bool GameEnds = false;
    public GameObject endMenuUI;

    void OnCollisionEnter2D(Collision2D exampleCol) 
    {
        if(exampleCol.collider.tag == "Obstacle")
        {
            endMenuUI.SetActive(true);
            Time.timeScale = 0.0001f;
            GameEnds = true;
        }
    }

    public void Retry()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }

    public void BackToMenu()
    {
        SceneManager.LoadScene("Menu");
    }

    public void Quit()
    {
        Debug.Log("Quitting game...");
        Application.Quit();
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = player.position.y.ToString("0");
    }
}
like image 806
Cem Ozsoy Avatar asked Nov 07 '22 10:11

Cem Ozsoy


1 Answers

You can keep the player using DontDestroyOnLoad

You could add this to the player:

void Awake() {
    DontDestroyOnLoad(transform.gameObject);
}

You could do other stuff like keeping just the data... but the easier way should be this one.

Keep in mind that the player will remain in you gameover screen.

In my opinion the best idea could be creating a new gameobject in your game scene called "GameOverScreen" and disable it until you need it.

like image 184
Chopi Avatar answered Nov 15 '22 06:11

Chopi