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
MediumClick a pad to build an Arrow tower on it.
- In
BuildPad, addpublic Tower tower;. - In
BuildManager, add[SerializeField] private Tower towerPrefab;. InUpdate, onMouse.current.leftButton.wasPressedThisFrame, cast a ray through the mouse. - If it hits a
BuildPadwhosetoweris null, setpad.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