Menu
CoddyTech

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 icon

Challenge

Medium

The player starts with 150 money, and an ArrowTower costs 50.

  1. In Tower, add a public int cost. The ArrowTower prefab sets it to 50.
  2. In GameManager, add a serialized int startMoney and a serialized TMP_Text moneyText, and a private int money that starts at startMoney. Show it as Money: 150 at the start and after every change.
  3. Add public bool TrySpend(int amount): when amount is more than the money, return false and change nothing; otherwise take it off, show the money and return true.
  4. In BuildManager, add a serialized field game (a GameManager). A free pad gets a tower only when game.TrySpend pays the prefab's cost; otherwise 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;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Tower Defense