본문 바로가기

유니티 3D기본(Roll A Ball)

16. 아이템 먹기 구현

플레이어 공이 아이템을 먹고, 점수가 1점씩 증가하는 걸 구현해 보겠습니다.

우선 PlayerBall 스크립트에 itemCount 변수를 선언합니다.

 

PlayerBall 소스코드

public int itemCount;


Item 소스코드

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

public class Item : MonoBehaviour
{
    public float rotateSpeed;

    void Update()
    {
        transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime, Space.World);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player") {
            PlayerBall player = other.GetComponent<PlayerBall>(); //PlayerBall의 스크립트 컴포넌트 가져오기
            player.itemCount++; //아이템 카운트 + 1
            gameObject.SetActive(false); //오브젝트 비활성화
        }
    }
}

 

마지막으로 Item 오브젝트에 isTrigger을 꼭 체크해야 onTrigger 함수를 호출할 수 있습니다.

 

 

결과