Money
Lesson 12 of 25 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
MediumTowers cost money: 150 to start, 50 an Arrow.
Tower: addpublic int cost = 50;.GameManager: add[SerializeField] private int startMoney = 150;,[SerializeField] private TMP_Text moneyText;andprivate int money;, shown asMoney: 150.public bool TrySpend(int amount): false ifamount > money; else take it, show it, true.BuildManager: add[SerializeField] private GameManager game;; build only ifgame.TrySpend(towerPrefab.cost), else 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;
}
}
All lessons in Unity Game: Tower Defense
Practice on your own: Unity playground