Menu
CoddyTech

Build Pads

Lesson 5 of 18 in Coddy's Unity Game: Tower Defense course.

The player builds towers by clicking the build pads, the grey squares beside the path. A click happens on the screen, in pixels, and the pads are in the 3D world, so the click becomes a ray. Camera.main.ScreenPointToRay(point) returns the ray that starts at the camera and goes through that screen point into the scene, and Physics.Raycast follows it and reports the first collider it hits: the one the player sees under the mouse. A paint tool that colors the block you click:

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 Paintable block))
    {
        block.Paint(brushColor);
    }
}

The second half of the && runs only when the ray hit something, so hit is filled in. TryGetComponent then asks whether the thing hit is one you care about: the ray also hits the ground, the path and the trees, which have no Paintable, so those clicks do nothing.

Every scene here uses Unity 6's Input System only, so Mouse.current reads the mouse. Its position is in screen pixels, which is what ScreenPointToRay expects.

challenge icon

Challenge

Medium

The pads have a BuildPad script, and the Game object has a BuildManager whose towerPrefab is the ArrowTower prefab.

  1. In BuildPad.cs, add a public field tower of type Tower: the tower built on this pad, or null.
  2. In BuildManager, add a serialized private field towerPrefab (a Tower). In Update, when the left mouse button is pressed this frame, cast a ray from the camera through the mouse.
  3. When the ray hits a collider that has a BuildPad, and that pad has no tower yet, instantiate towerPrefab at the pad's position and store the new tower in the pad's tower. A pad with a tower, or anything that is not a pad, does nothing.

Press Play and click some pads, then Check.

Try it yourself

using UnityEngine;

// Comes later: clicking build pads to place towers, the shop and the tower panel.
public class BuildManager : MonoBehaviour
{
}
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