官术网_书友最值得收藏!

Scoring enemy hits

As with most games, we need a scoring system to show how well the player has done at the end of the game. Typically, with side-scrolling shooter games, the player is rewarded for each kill they make. If we turn to our game framework diagram, we can see that ScoreManager is hooked up to GameManager like ScenesManager was:

Our code for adding a scoring system will once again be minimal. We also want flexibility so that different enemies are worth different points. We also want it so that when we add another enemy to our game with a different scoring point, we can avoid altering our code each time.

We will be working with the following scripts in this section:

  • EnemyWave
  • ScoreManager
  • ScenesManager
  • SOActorModel

Seeing as the scoring system is an integral factor in our game, it would make sense to add a simple integer to SOActorModel that injects common values into our game objects. This trend will then follow on to other scripts. Let's start adding some code to our already-made scripts before we introduce ScoreManager.

Preparing the code for the ScoreManager script

If you recall back to Chapter 1, Setting Up and Structuring Our Project, we spoke about the SOLID principles and how important it is to add to our code rather than change it, else we risk errors and our code may start mutating toward being unfit for purpose. In order to prepare, we will add code to the scripts that we have already made to fit our ScoreManager script into place. Let's start with the SOActorModel first. Follow these steps:

  1. Open the SOActorModel script from the Project window.
  2. Anywhere within our list of variables' SOActorModel script, add the following code, which will be used to contain the enemy's score:
          public int score;
        
  1. Save the SOActorModel script.

Before we add more code to the other scripts to fit ScoreManager into our game, we need to acknowledge that we have made a change to our ScriptableObject template.

Let's check our BasicWave Enemy scriptable object in the Unity editor. Follow these steps:

  1. From the Project window, navigate to the Assets/Script/ScriptableObject folder.
  2. Click once on BasicWave Enemy and you will see that the Inspector window has a Score input field.
  3. Give the Score field of BasicWave Enemy a value of your choice. I'm giving it a value of 200. It really doesn't matter what value you give it as long as it's more than 0. The following screenshot shows the BasicWave Enemy section with its updated Score value:

We have updated the BasicWave Enemy scriptable object. We now need to focus on the EnemyWave script to create and receive this new variable.

Open theEnemyWavescript and enter the following code.

  1. At the top of the script where we have our health, travelSpeed, and so on global variables, add an extra variable to the list:
          int score;
        

We now need to update the score variable from the ScriptableObject value.

  1. In the EnemyWave script, scroll down until you find the ActorStats method, then add the following extra line of code:
          score = actorModel.score;
        

The EnemyWave script now has a score variable that is set from the value given to it by SOActorModel. The last thing we need to do is send the score value to ScoreManager when the enemy dies due to the actions of the player. Before we do that, let's create and code our ScoreManager script.

Setting up our ScoreManager script

The purpose of the ScoreManager script is to total up the score of the player during their game, concluding when they arrive at the gameOver scene. We could also give the ScoreManager script other score-related functionality, such as the ability to store our score data on the device that we are playing the game on or to send the score data to a server for an online scoreboard. For now, we will keep things simple and just collect the player's score.

We can create and add our ScoreManager script to the game framework, as follows:

  1. Create and attach a script called ScoreManager to the GameManager game object, similar to how we did with ScenesManager.

If you can't remember how to do this, then check the Setting up our ScenesManager scriptsection ofthis chapter. The following screenshot showsScoreManagerattached to theGameManagergame object in theInspectorwindow:

  1. Next, we are going to open the ScoreManager script and add code that will hold and send score data. Open the ScoreManager script and enter the following code:
          using UnityEngine;
        
Importing the usual UnityEngine library allows the majority of the functionality of Unity to work, such as MonoBehaviour being recognized in inheritance.
  1. Continue on by checking and entering the name of the class:
          public class ScoreManager : MonoBehaviour
{

This is a public class with ScoreManagerinheriting MonoBehaviour to increase the functionality of the script.

  1. Next, we add our variables and properties to our script. The only value we are concerned about is playerScore, which is private to the script (as we don't want other classes to have access). This variable is also set to static, meaning we don't need duplicate references for this variable.

Following on from this is our public property, which gives outside classes access to the playerScore variable. As you'll notice, the PlayerScorepropertyreturns an integer. Within this property, we use thegetaccessor to return our privateplayerScoreinteger. It is a good habit to keep our variables private, else you risk exposing your code to other classes, which can result in errors. The following code shows you how to complete this step:

    static int playerScore;
public int PlayersScore
{
get
{
return playerScore;
}
}
  1. We will now move on to the SetScore method; it is public and doesn't return a value (void), with the SetScore name taking in an integer parameter named incomingScore. Within this method, we use incomingScore to add to the playerScore script (as its total score):
  public void SetScore(int incomingScore)
{
playerScore += incomingScore;
}
}
  1. The last method to add is the ResetScore method. Enter the following code:
 public void ResetScore()
{
playerScore = 00000000;
}
}

We can call this method at the beginning orendof a game to stop the score from carrying on into the next game.

  1. Save the script.

As mentioned earlier, we can now return to the EnemyWave script to send the value of the enemy's score points to the ScoreManagers method, SetScore, thereby adding them to the player's total score:

  1. Open the EnemyWave script from the Project window and scroll down to the OnTriggerEnter Unity function.
  2. Within the scope of the if statement labeled if (health <= 0), enter the following line of code at the top of its scope:
          GameManager.Instance.GetComponent<ScoreManager>().SetScore(score);
        

When this particular enemy dies as a result of the player, this line of code will send the enemy's score value directly to the playerScore variable and increment it toward its total until the player loses all of their lives.

  1. Finally, to confirm the score has totaled correctly, let's do what we did before with the playerLives integer in the LifeLost method of the GameManager script and add a Debug.Log message to the Console window.

  1. In the ScenesManager script under the GameOver() method, add the following line of code at the top within its scope:
Debug.Log("ENDSCORE: " +
GameManager.Instance.GetComponent<ScoreManager>
().PlayersScore);

This code will tell us how much the player has scored because it directly accessesScoreManagerand grabs thePlayerScorepropertywhen the game is over. The following screenshot shows an example of a totaled score:

  1. Finally, save all the scripts.

In this section, we introduced the ScoreManager script with its basic working structure of totaling up our end score and displaying the final count in the Console window. We have also added more code to a selection of scripts without deleting and changing any of their content. Next, we will be doing something different that doesn't involve any coding but gets us more familiar with Unity's sound components.

主站蜘蛛池模板: 巨野县| 亳州市| 平度市| 通河县| 万州区| 盈江县| 巴马| 游戏| 驻马店市| 嘉鱼县| 灯塔市| 泾阳县| 邵阳县| 齐齐哈尔市| 安仁县| 浦城县| 镇远县| 绩溪县| 青河县| 崇州市| 潞城市| 加查县| 安阳市| 马边| 东乌珠穆沁旗| 诏安县| 玛沁县| 砀山县| 库尔勒市| 余干县| 平昌县| 嘉定区| 云浮市| 玉门市| 晋中市| 蛟河市| 金寨县| 海丰县| 湘乡市| 金山区| 尚志市|