Menu
CoddyTech

Build Pads

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

The player builds towers by clicking the grey build pads. A click is a point on the screen, so it becomes a ray: Camera.main.ScreenPointToRay returns the ray from the camera through that point, and Physics.Raycast reports the first collider it hits, the one under the mouse.

Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
if (Physics.Raycast(ray, out RaycastHit hit))
{
    Debug.Log("Clicked " + hit.collider.name);
}

The ray also hits the ground, the path and the trees. hit.collider.TryGetComponent(out BuildPad pad) asks whether the thing hit is a pad, so other clicks do nothing. Every scene here uses the Input System, so Mouse.current reads the mouse (using UnityEngine.InputSystem;).

challenge icon

Challenge

Medium

Click a pad to build an Arrow tower on it.

  1. In BuildPad, add public Tower tower;.
  2. In BuildManager, add [SerializeField] private Tower towerPrefab;. In Update, on Mouse.current.leftButton.wasPressedThisFrame, cast a ray through the mouse.
  3. If it hits a BuildPad whose tower is null, set pad.tower = Instantiate(towerPrefab, pad.transform.position, Quaternion.identity);.

Press Play and click pads: one tower stands on each. 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
{
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground