Building UI in Unity
Creating a Score board and Lives Counter (part 2)
Now that we have the text and image elements of our UI within the canvas and is set perfectly. It is time to implement the codes and allow the scripts to update and communicate with other scripts and make the Lives visualizer and Score counter work.
Understanding the Logic for Score text
The pseudo codes behind the score text component is rather easy to understand:
When a laser hits an enemy, the player will gain 10 points and the score board would update and keep track of the accumulated points.
Linking the UI Manager to the Player
Implementing the script would require a bit more complex thinking. First create a C# script to function as the UI manager. We can attached this script into the Canvas. Next within the UI Manager script we need a private variable that looks for the text component. You would have noticed that since this is an text element that is part of the Unity UI element, we need to grant access to the Unity Engine UI. Once you have gain access to it, the “text” handle can be used without error.
Now looking at the player script, since this file is housing all of the major functions, it is only correct to place the score system within this script as well. We start by creating an private integer handle called “_scores,” This will be the actual tracker for the amount of points acquired. Then we need access to the UI manager script so we have to get access to that as well.
Finally we need a new public method to call upon and update the UI manager text and also trigger the “adding of points” to the score board.
As mentioned before with the pseudo code, it is actually the laser hitting the enemy that gives the points. So the action of destroying the enemy is what triggers the “gaining of points.” Thus within the enemy script is where we will be triggering the newly created public method from the player script.
In the Player script and UI Manager, we will be creating the “Update Score” public method so that the two scripts can communicate. So every time an Enemy is destroyed via laser, it tell the player to add 10 points to the score board, at the same time it also tells the UI Manager to update the actual score text.