
체력바를 만들어봅시당~ 큰 그림은 ScriptableObject인 HitPoint을 만들고, 이에 대한 정보를 HealthBar와 Player가 같이 쓴다. HealthBar cs와 Player cs가 어떻게 얽혀있는지 파악하는게 중요하다.

사담으로 타일맵 사용이랑 디버깅 방법들도 정리해서 올려야하는데 ㅋㅋㅋ 언제하지...
HitPoint cs는 너무나 간단하다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "HitPoints")]
public class HitPoints : ScriptableObject
{
public float value;
}
value는 게임 시작할 때 플레이어의 처음 체력으로 쓸거다.

ScriptableObjects에 HitPoints 만들어줍시다.
우선 Player는 Character class를 상속하고, 모든 Character는 체력이 필요하므로 Character cs를 수정한다. 최대체력과 시작체력을 만들어준다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Character : MonoBehaviour
{
public HitPoints hitPoints;
public float maxHitPoints;
public float startingHitPoints;
}
Player cs의 Start()에 내용을 추가한다.
hitPoints.value = startingHitPoints;

인스펙터창으로 돌아가서 최대체력과 시작체력을 정해준다.
HealthBar cs를 작성하자.
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public HitPoints hitPoints;
[HideInInspector]
public Player character;
public Image meterImage;
public Text hpText;
float maxHitPoints;
private void Start()
{
maxHitPoints = character.maxHitPoints;
}
private void Update()
{
if (character != null)
{
meterImage.fillAmount = hitPoints.value / maxHitPoints;
hpText.text = "HP:" + (meterImage.fillAmount * 100);
}
}
}
체력바의 최대 체력도 캐릭터와 동일해야한다. 따라서 character.maxHitPoints를 대입한다.
또 체력바의 meterImage는 체력에 따라 이미지가 점점 채워진다. hitPoints가 지금 플레이어의 체력이므로 hitPoints의 value를 최대 체력으로 나눠준 값만큼 이미지를 채운다.
Player cs를 수정하자. Start()에 추가한다.
hitPoints.value = startingHitPoints;
healthBar = Instantiate(healthBarPrefab);
healthBar.character = this;
healthBar의 character가 Player임을 명시해준다.
Player의 체력은 최대체력보다 낮을 때만 추가되어야한다.
public bool AdjustHitPoints(int amount)
{
if (hitPoints.value < maxHitPoints)
{
hitPoints.value = hitPoints.value + amount;
print("Adjusted HP by: " + amount + ".New Value: " + hitPoints.value);
return true;
}
return false;
}
Player의 체력이 최대 체력보다 크면 아무일도 발생하지 않도록 bool을 사용한다. 마지막으로 하트를 먹으면 체력이 바뀌도록 Player 코드를 수정한다.
switch (hitObject.itemType)
{
case Item.ItemType.COIN:
shouldDisappear = inventory.AddItem(hitObject);
break;
case Item.ItemType.HEALTH:
shouldDisappear = AdjustHitPoints(hitObject.quantity);
break;
default:
break;
}
부딪힌 게임 오브젝트의 quantity만큼 체력이 변동한다. 하트를 먹으면 체력이 10만큼 증가한다. 그리고 AdjustHitPoints가 true를 반환하므로 shouldDisappear도 true가 되어 먹은 하트는 Active(false)가 된다. 두둥.

하트를 먹은만큼 체력바의 게이지가 차오른다. 하트도 뿅 사라졌다.