Money
Lesson 6 of 18 in Coddy's Unity Game: Tower Defense course.
Towers cost money. The money belongs to the GameManager, and the BuildManager asks it to pay. Asking and paying are one step: a method that checks the money, takes it when there is enough, and says with a bool whether it did, the way Dictionary.TryGetValue answers. A vending machine's wallet:
public bool TryPay(int price)
{
if (price > coins)
{
return false;
}
coins -= price;
coinText.text = coins + " coins";
return true;
}No caller can pay without the check, and the coins never go below zero, because nothing else changes them. The price lives on the prefab: a field of its own script, set in the prefab's Inspector. A prefab is a loaded object like any other, so snackPrefab.price can be read before anything is instantiated, to decide whether it should be.
Challenge
MediumThe player starts with 150 money, and an ArrowTower costs 50.
- In
Tower, add a public intcost. The ArrowTower prefab sets it to 50. - In
GameManager, add a serialized intstartMoneyand a serialized TMP_TextmoneyText, and a private intmoneythat starts atstartMoney. Show it asMoney: 150at the start and after every change. - Add
public bool TrySpend(int amount): whenamountis more than the money, return false and change nothing; otherwise take it off, show the money and return true. - In
BuildManager, add a serialized fieldgame(a GameManager). A free pad gets a tower only whengame.TrySpendpays the prefab'scost; otherwise logNot enough money.
Press Play and build until the money runs out, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
[SerializeField] private int startLives = 20;
[SerializeField] private TMP_Text livesText;
private int lives;
void OnEnable()
{
Enemy.ReachedBase += OnReachedBase;
}
void OnDisable()
{
Enemy.ReachedBase -= OnReachedBase;
}
void Start()
{
lives = startLives;
ShowLives();
}
void OnReachedBase(Enemy enemy)
{
lives -= enemy.data.damage;
ShowLives();
}
void ShowLives()
{
livesText.text = "Lives: " + lives;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.