Tag

게임 오브젝트에 태그를 넣어 관리할 수 있다.

- 태그로 검사 가능

Tag

 

목표

1. ObjectHit 스크립트에서 태그로 충돌을 검사하여 Player일 때 색을 변경하고 자신의 Tag를 Hit으로 변경하기

2. Scorer 스크립트에서 태그로 충돌을 검사하여 Hit인지 검사하고 Hit이 아니면 점수를 올리기

ObjectHit.cs

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

public class ObjectHit : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        // 충돌한 객체의 게임 오브젝트의 태그가 Player이면
        if (collision.gameObject.tag == "Player")
        {
            GetComponent<MeshRenderer>().material.color = new Color(1, 0, 0, 1); // red
            // ObjectHit이 있는 해당 오브젝트의 tag를 Hit으로 변경함
            gameObject.tag = "Hit";
        }
    }
}

Scorer.cs

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

public class Scorer : MonoBehaviour
{
    // 점수를 담을 변수
    int hits = 0;

    private void OnCollisionEnter(Collision collision)
    {
        // 충돌한 객체의 태그가 Hit이면(이미 충돌한 객체이면) 스킵
        // if (collision.gameObject.tag != "Hit")과 반대
        if (collision.gameObject.tag == "Hit")
            return;
        
        hits++;

        // 문자열 + 변수이름 하면 붙어서 출력 (문자열변수 이런 식) 
        Debug.Log($"You've bumped into a thing this many times: " + hits); 
    }
}

Tag로 검사

+ Recent posts