Menu
CoddyTech

Recap: Key and Door

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 20 of 63.

challenge icon

Challenge

Easy

A locked gate stands in the wall, and a key lies on the floor. Player.cs moves the player with the arrows and has a hasKey field. The Key and the Doorway in front of the gate are triggers. Write their scripts:

  • Key: when the player touches it, set the player's hasKey to true, log Got the key and remove the key. Nothing else can take it: a ball rolling over it leaves it where it is.
  • Door: when the player walks into the doorway with the key, hide gate and log The door opens. Without the key, log Locked and leave the gate shut.

Press Play, try the door, fetch the key and try again, then Check.

Try it yourself

using UnityEngine;

public class Key : MonoBehaviour
{
    // The player takes the key; nothing else does
}

All lessons in Physics and Gameplay