Menu
CoddyTech

ドア

CoddyのUnityジャーニー「物理演算とゲームプレイ」セクションの一部。レッスン 71/71。

この課題で、このセクションは完了です。トリガーとなるプレート、1つのスクリプトにまとめられたコード、そして出入り口が空くまで待つコルーチンで動くドアについて学びます。

challenge icon

チャレンジ

難しい

Unlockedになったらドアを開け、後で再び閉じます。ただし、プレイヤーがいる間は閉じないでください。

  1. IEnumerator OpenDoor()を記述します。door.SetActive(false);を実行し、その後にyield return new WaitForSeconds(openTime);を実行します。
  2. 次に、while (Physics.CheckSphere(doorway.position, 1f, LayerMask.GetMask("Player")))の間、yield return null;を実行します。
  3. 最後に、door.SetActive(true);を実行し、Door closedをログに出力します。Unlockedをログに出力した後、StartCoroutine(OpenDoor());で開始します。

「プレイ」を押し、ドアのロックを解除して外に出ます。その後、「確認」を押します。

自分で試してみよう

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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

物理演算とゲームプレイのすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド