We will now a total score display to the End Screen scene.
Copy the following code for the DisplayScore script and save the file:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class score : MonoBehaviour
{
public TextMeshProUGUI scoreUI;
//Static variable allows to use the current value in the variable in different gamescene
static int final_score;
public int scorepoint;
private float timer = 0.0f;
void Update()
{
if (timer < 1)
{
timer = timer + Time.deltaTime;
}
else
{
scorepoint++;
Debug.Log(SceneManager.GetActiveScene().buildIndex);
if (SceneManager.GetActiveScene().buildIndex == 1)//stops updating the final_score when the game moves to the GameOver scene
{
final_score = scorepoint;
}
timer = 0;
}
scoreUI.text = "Score: " + final_score.ToString();
}
}
Navigate to the Scenes folder
Click on the End Screen scene
Click on the dropdown of Canvas > Score, in the Inspector window:
- From the Scripts folder, drag the DisplayScore script
- Drag the "TextMeshPro - Text (UI)" script into the placeholder