Scripting Damage into the PlayerStats Component

How do we tell the player that they’ve been injured? We could do it from the script that deals damage, but there could be many such scripts created as the game grows, leading to a lot of unnecessarily duplicated code that you’d have to maintain. Instead, we will add a TakeDamage() function to the PlayerStats script. We will call this function whenever the player is hurt, and it will handle the necessary math and effects from one centralized location.

Update your PlayerStats script to match Listing 9.5 now.

Listing 9.5 Updating the PlayerStats Script

public class PlayerStats : MonoBehaviour{  public int health = 6;  public int coinsCollected = 0;  public void CollectCoin(int ...

Get Learning 2D Game Development with Unity®: A Hands-On Guide to Game Creation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.