Day 23: Ease of Building UI Elements in Unity
Objective: Today is all about connecting code and UI!
We’ll start with a score system. Every time an enemy is killed we’ll add 10 points for now. We’ll start off by adding a text UI to the hierarchy.
Under the Score text, in the rect transform, reset the transform. While holding alt and shift, click anchor preset and set the position to top right. You can adjust the position from there. This will keep the text located in this area when the screen is resized.
In the inspect scroll down till you see the text component. Here you can change the text font,color, size, and more. If you adjust the font size and the text disappear from the screen, you will need to adjust the rect to get the text to show back up.
Now on to the Code. We’ll start off by creating a UIManager script and add it to the Canvas game object.
In the script to use the text component we will need to add the namespace UnityEngine.UI to the top of the script.
Now to get a reference to the text object. Don’t forget to assign the text object in the inspector.
To update the score text, we are going to create a function that gets a int passed into it. Then we will set the _scoreText to a string of text plus the int. I like to use string interpolation when assigning string of text with variables in them. You do this by add $ in front of the first Quotation mark, as seen below. For the variable that is being read to string will be in a set of {} inside the quotation marks.
Now to call this function. We’ll call this function from the player script. On the player script we will need a reference to the UIManager. As well as a variable to collect the score.
Next step will to find the UIManager and make sure it is not null.
We need a way to add to the score but only when an enemy dies. Let’s add another function called AddScore. In the AddScore, we will call the SetScoreText from the UIManager and pass in the score variable.
To call this, we need to move over to the enemy script.
In the enemy script we have a local varible for the player script. We need to set this to a global variable and find the player object before the OnTriggerEnter is called.
Down in the OnTriggerEnter, we want to call add score when the enemy is destroyed by a laser, We’ll check to make sure the player isn’t null and than call the function.
And that’s it. Every time you kill you enemies you can get points!