Basic UI Communication Script — Unity
For the 2D Space Shooter, the score will record the number of enemies destroyed by laser hit, displaying it on a 2D overlay screen that renders on top of the camera called Canvas. The Canvas needs a UI Manager script to establish communication with the score text. This text element uses the TMPro package.
- Score text script implementation
- Canvas SetUp
To create the score text, point inside the Hierarchy and right-click UI-> Text — TextMeshPro. The canvas will be created along and as a parent object of the Score_Text. On the canvas create a new script called UIManager. The packages UnityEngine.UI and TMPro must be used. To record and constantly update the display text element, the script requires a reference to the text object in the hierarchy and a public int of number of ships destroyed. The NewTakedown() updates the display text.
using UnityEngine.UI;
using TMPro;
[SerializeField]
private TMP_Text _destroyedScore;
public int shipsDestroyed;
void Start()
{
shipsDestroyed= 0;
_destroyedScore.text = "Destroyed: " + shipsDestroyed;
}
public void NewTakedown(int playerScore)
{
_destroyedScore.text = "Destroyed: " + playerScore.ToString();
}
The player script needs a reference to the score text, an int of destroyed enemies, and a reference to the UIManager script. Find the Canvas game object and get the component script. With this reference, the player can call the NewTakedown() method, which updates the displayed text.
[SerializeField] private TMP_Text _scoreText;
[SerializeField] private int _destroyed = 0;
private UIManager _uiManager;
void Awake()
{
_uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
if (_uiManager == null)
{
Debug.LogError("UI is null");
}
}
public void AddDestroyed(int points)
{
_destroyed += points;
_uiManager.NewTakedown(_destroyed);
}
The enemy script calls the AddDestroyed(enemy value), allowing a modular enemies system that each kind provide a different score value. For this example, the enemy would just call 2 points, which can be switched through and array of int values.
//reference to player
private Player _player;
private void Start()
{
_player = GameObject.Find("Player").GetComponent<Player>();
}
private void OnTriggerEnter2D(Collider2D other)
{
//currently this enemy adds 2 points
if (other.tag == "Laser")
{
Destroy(other.gameObject);
if (_player != null)
{
_player.AddDestroyed(2);
}
Destroy(this.gameObject);
}
}
Set the UI Scale Mode to Scale with Screen Size inside the Canvas Inspector; don’t forget to add text reference to the script.
This is a simple chain of three methods that create a simple and powerful score system; this score method could extend quite easily to a modular score system that reacts to diverse input values rather than simply counting enemies killed, rewarding players much faster through high or low scores and avoid linear scoring.
It all took just one right-click element and a bit of coding.