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
HardOpen the door on Unlocked, and close it again later, never on the player.
- Write
IEnumerator OpenDoor():door.SetActive(false);, thenyield return new WaitForSeconds(openTime);. - Then
while (Physics.CheckSphere(doorway.position, 1f, LayerMask.GetMask("Player"))),yield return null;. - Last,
door.SetActive(true);and logDoor closed. Start it withStartCoroutine(OpenDoor());after loggingUnlocked.
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;
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground