Menu
CoddyTech

The Door

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

This challenge finishes the section: plates that are triggers, a code kept in one script, and a door run by a coroutine that waits for the doorway to clear.

challenge icon

Challenge

Hard

Open the door on Unlocked, and close it again later, never on the player.

  1. Write IEnumerator OpenDoor(): door.SetActive(false);, then yield return new WaitForSeconds(openTime);.
  2. Then while (Physics.CheckSphere(doorway.position, 1f, LayerMask.GetMask("Player"))), yield return null;.
  3. Last, door.SetActive(true); and log Door closed. Start it with StartCoroutine(OpenDoor()); after logging Unlocked.

Press Play, unlock the door and get out. Then Check.

Try it yourself

using System.Collections;
using UnityEngine;

public class CodeLock : MonoBehaviour
{
    [SerializeField] private Renderer[] plates;
    [SerializeField] private GameObject door;
    [SerializeField] private Transform doorway;
    [SerializeField] private float openTime = 4f;
    private int next = 1;

    public void Press(int number)
    {
        if (number == next)
        {
            Debug.Log("Plate " + number);
            next++;
            if (next > 3)
            {
                Debug.Log("Unlocked");
                next = 1;
            }
        }
        else
        {
            Debug.Log("Wrong plate");
            next = 1;
            StartCoroutine(Flash());
        }
    }

    IEnumerator Flash()
    {
        foreach (Renderer plate in plates)
        {
            plate.material.color = Color.red;
        }
        yield return new WaitForSeconds(1f);
        foreach (Renderer plate in plates)
        {
            plate.material.color = Color.gray;
        }
    }

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay

Practice on your own: Unity playground