Menu
CoddyTech

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 icon

Challenge

Medium

Towers cost money: 150 to start, 50 an Arrow.

  1. Tower: add public int cost = 50;.
  2. GameManager: add [SerializeField] private int startMoney = 150;, [SerializeField] private TMP_Text moneyText; and private int money;, shown as Money: 150.
  3. public bool TrySpend(int amount): false if amount > money; else take it, show it, true.
  4. BuildManager: add [SerializeField] private GameManager game;; build only if game.TrySpend(towerPrefab.cost), else log Not 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