Menu
CoddyTech

Select a Tower

Lesson 17 of 25 in Coddy's Unity Game: Tower Defense course.

Clicking a tower opens a panel with its level and what the next level would bring. A click on a tower hits one of its parts, the base or the head, which are children of the tower, so hit.collider.GetComponentInParent<Tower>() finds the tower they belong to: it looks on the object hit, then up its parents.

The panel shows the stats now and at the next level side by side, so the player sees what an upgrade buys:

towerStatsText.text = "Damage " + data.DamageAt(level) + " > " + data.DamageAt(level + 1);
challenge icon

Challenge

Medium

Click a tower to open its panel.

  1. In BuildManager, add private Tower selected;. A click on a tower selects it; a click on anything else selects nothing.
  2. Add serialized towerPanel (a GameObject) and towerNameText, towerStatsText, upgradeLabel (TMP_Text). The panel shows only while a tower is selected.
  3. Fill it: Arrow level 1, Damage 2 > 3 and Range 4.5 > 5 on two lines, Upgrade 40.

Press Play, build a tower and click it. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using TMPro;

public class BuildManager : MonoBehaviour
{
    [SerializeField] private GameManager game;
    [SerializeField] private Tower[] shop;
    [SerializeField] private Button[] shopButtons;
    [SerializeField] private Color chosenColor = new Color(1f, 0.85f, 0.3f);

    private Tower chosen;

    void Start()
    {
        for (int i = 0; i < shop.Length; i++)
        {
            Tower prefab = shop[i];
            shopButtons[i].GetComponentInChildren<TMP_Text>().text = prefab.data.towerName + "\n" + prefab.data.cost;
            shopButtons[i].onClick.AddListener(() => Choose(prefab));
        }
        Choose(shop[0]);
    }

    void Choose(Tower prefab)
    {
        chosen = prefab;
        for (int i = 0; i < shop.Length; i++)
        {
            shopButtons[i].image.color = shop[i] == chosen ? chosenColor : Color.white;
        }
    }

    void Update()
    {
        if (!Mouse.current.leftButton.wasPressedThisFrame)
        {
            return;
        }

        Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
        if (Physics.Raycast(ray, out RaycastHit hit) && hit.collider.TryGetComponent(out BuildPad pad))
        {
            Build(pad);
        }
    }

    void Build(BuildPad pad)
    {
        if (pad.tower != null)
        {
            return;
        }

        if (!game.TrySpend(chosen.data.cost))
        {
            Debug.Log("Not enough money");
            return;
        }

        pad.tower = Instantiate(chosen, pad.transform.position, Quaternion.identity);
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground