public class ItemBox : MonoBehaviour
{
// 아이템박스 Renderer를 담을 변수 선언
private Renderer myRenderer;
// 컬러 색상을 담을 변수 선언
public Color touchColor; // public이어서 Unity Inspector에서 편집 가능 (파란색으로 설정)
private Color originalColor; // 기존 색상 정보를 담을 변수 선언
void Start()
{
// 게임이 시작됐을 때 나 자신의 Renderer를 가져오기
myRenderer = GetComponent<Renderer>();
// 기존 색상 정보 담기
originalColor = myRenderer.material.color;
}
// 오브젝트가 Trigger(뚫고 지나갈 수 있는 오브젝트)인 Collider와 충돌했을 때 유니티가 자동으로 호출
// Enter 충돌을 한 그 순간 호출
void OnTriggerEnter(Collider other)
{
// other(충돌한 Collider 오브젝트)의 Tag가 "EndPoint" 인 경우
if(other.tag == "EndPoint")
{
// 아이템박스의 Renderer 컴포넌트의 materials 색상 변경하기
myRenderer.material.color = touchColor;
}
}
// Stay 붙어있는 동안 호출
void OnTriggerStay(Collider other)
{
if(other.tag == "EndPoint")
{
myRenderer.material.color = touchColor;
}
}
// Exit 충돌했다가 떼어질 떄 호출
void OnTriggerExit(Collider other)
{
if(other.tag == "EndPoint")
{
// 색상 기존 색상으로 다시 변경하기
myRenderer.material.color = originalColor;
}
}
}
public bool isOveraped = false;
// Enter & Stay
isOveraped = true;
// Exit
isOveraped = false;
모든 ItemBox(3개)가 EndPoint에 충돌했을 때 승리했다는 로직을 추가
GameManager 스크립트 생성
Assets > Create > C# Script > GameManager
GameManager 스크립트를 적용할 Empty GameManager 오브젝트 생성
Hierarchy > Create Empty > GameManager
생성한 GameManager 오브젝트에 GameManager 스크립트 적용 (Drag & Drop)
스크립트 코드 작성
public class GameManager : MonoBehaviour
{
// 모든 ItemBox(3) 정보를 담을 배열 생성
// GameManager 오브젝트 > Inspector > itemBoxes > Size 설정(3)
// 추가된 3개의 Element에 ItemBox 3개를 Drag & Drop으로 넣어줌
public ItemBox[] itemBoxes;
// 게임이 종료됐는지 알려주는 변수 선언
public bool isGameOver;
void Start()
{
// 게임 시작 시 isGameOver 초기값 설정
isGameOver = false;
}
void Update()
{
// 게임이 종료(승리)되었을 경우 함수(Update) 종료(return)
if(isGameOver == true)
{
return;
}
// ItemBox가 EntPoint에 몇개 도달했는지 정보를 담을 변수
int count = 0;
// ItemBox 오브젝트가 EndPoint에 도달했는지 체크
for(int i=0; i<3; i++)
{
if(itemBoxes[i].isOveraped == true)
{
count++;
}
}
// ItemBox 전부(3개)가 EndPoint를 모두 도달했을 경우
if(count >= 3)
{
Debug.Log("승리");
isGameOver = true;
}
}
}