해당 포스팅에서는 사운드오브좀비 게임에서 목숨 물약을 얻고
UI에 반영하는 내용을 담으려 한다.
위의 목표는 아래와 같은 요구사항이 필요하다.
물약과 충돌을 감지하기 위해 물약에 collider를 설정해준다.
Is Trigger도 체크!
물약에 새로운 script를 만든 뒤 OnTriggerEnter함수를 작성한다.
void OnTriggerEnter(Collider other)
{
//물약이 다른 object와 닿는다면 물약 object 삭제
Destroy(gameObject);
}
물약을 먹으면 UI 왼쪽 하단 목숨 표시에 목숨 + 1
왼쪽 하단 UI의 script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameSystemInfo : MonoBehaviour
{
public static GameSystemInfo Instance { get; private set; }
public Text LifeText;
void Awake()
{
Instance = this;
}
public void UpdateLife()
{
//UpdateLife() 함수가 호출되면 현재 목숨 값을 가져와
//정수로 변경 후 +1을 한 값을 다시 UI에 적용한다.
int life = int.Parse(LifeText.text)+1;
LifeText.text = life.ToString();
}
}
script와 object를 연결해준다.
void OnTriggerEnter(Collider other)
{
//물약이 다른 object와 닿는다면 물약 object 삭제 및
//UpdateLife() 함수 호출
GameSystemInfo.Instance.UpdateLife();
Destroy(gameObject);
}
기본 목숨은 3이며 물약을 먹을 때마다 목숨이 하나씩 늘어난다.
물약은 스테이지 곳곳에 배치해 놓을 예정이다.