(Unity)プレーヤーとの距離が一定以下になったら、オブジェクトの色とTagを変化させる(応用;「密です」ゲーム)

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mitu : MonoBehaviour
{
    private GameObject player;
    private string initialTag;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");

        // 最初のtagを取得する
        initialTag = this.gameObject.tag;
    }

    void Update()
    {
        // 自分とPlayerの距離を取得
        float dis = Vector3.Distance(transform.position, player.transform.position);

        if(dis < 5)
        {
            // 自分を赤色にする。
            GetComponent<MeshRenderer>().material.color = Color.red;

            // tagを「Mitu」に変更する。
            this.gameObject.tag = "Mitu";
        }
        else
        {
            // 元の色(白)に戻す。
            GetComponent<MeshRenderer>().material.color = Color.white;

            // 最初のtagに戻す。
            this.gameObject.tag = initialTag;
        }
    }
}

(設定&実行結果)

  • このスクリプトを自動で動きまわる敵に設定する。

  • Tagも変化

 


(応用;「密です」ゲーム)

<ルール>

  • 「密な状態」が発生したらゲームオーバー

<発想>

  • 「密な状態」=「プレーヤーと一定の距離内に複数の敵が存在する」

<上記の活用>

  • 「Mitu」のTagが付いているものが一定数を超えたらゲームオーバー!

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MituManager : MonoBehaviour
{
    private GameObject[] enemies;
    public GameObject gameOverLabel;


    private void Start()
    {
        StartCoroutine(MituCheck());
    }

    private IEnumerator MituCheck()
    {
        while(true)
        {
            enemies = GameObject.FindGameObjectsWithTag("Mitu");

            if (enemies.Length >= 3)
            {
                gameOverLabel.SetActive(true);
            }

            yield return new WaitForSeconds(0.5f);
        }
    }
}

(実行結果)

  • 「Mitu」のTagが付いているものが3体を超えたらゲームオーバー!