Now that we have a visible HUD, we need to add logic to have it update when players score. This tutorial will add code to the ScoreHud to update the displayed text according to public properties which will be set by GameScreen whenever a goal is scored.
Adding Team Score Properties
First we’ll be adding properties to the Hud object for the scores of each of the players. We could do this purely in code, but Glue provides a convenient way to set the score values to integers.
We will be combining two Glue features for this:
- Tunneling variables – Creating a variable in an entity which is tied to the variable of a contained object. In this case we’ll be creating variables which are tied to each of the score Texts’ DisplayText variable.
- Built-in casting of the variable type – although DisplayText is a string, we’ll tell Glue that we intend to use it as an integer.
To do this:
- Expand ScoreHud’s Objects in Glue
- Drag+drop the Team1Score onto the Variables item
- Select DisplayText as the variable
- Set the Alternative Name to Score1
- Set the Variable Type to int
- Click OK
Repeat the steps above, but this time use Team2Score, and create a variable called “Score2”.
Updating the HUD
Now that the ScoreHud can react to score changes, the ReactToNewScore can be modified to update the HUD. To do this, modify the ReactToNewScore method in GameScreen as follows:
PlayerBallInstance.X = 180;
PlayerBallInstance.Y = 0;
PlayerBallInstance.Velocity = Vector3.Zero;
PlayerBallInstance.Acceleration = Vector3.Zero;
PlayerBallInstance2.X = -180;
PlayerBallInstance2.Y = 0;
PlayerBallInstance2.Velocity = Vector3.Zero;
PlayerBallInstance2.Acceleration = Vector3.Zero;
PuckInstance.X = 0;
PuckInstance.Y = 0;
PuckInstance.Velocity = Vector3.Zero;
ScoreHudInstance.Score1 = player1Score;
ScoreHudInstance.Score2 = player2Score;
If we run the game now we’ll notice that scores start out at 0 and increments whenever a player scores a goal.
If you are seeing a conversion error similar to Cannot implicitly convert type 'int' to 'string' , then you may need to modify the variables for Score1 and Score2. See the steps above where the Variable Type is set to int.
If you’ve already created the variables, you can set the variable conversion:
- Select the Score1 variable
- Select the Properties tab
- Change OverridingPropertyType to int
Well, that was easy! Now we have scoring working. At this point we could call the game done. The next tutorial will be adding some extra finishing touches to the controls to make it more competitive and make the game play deeper.