Unity 3d 게임 Hp bar 만들기
💡 유니티 3d게임에서 hp 여러 캐릭터 위에 체력바를 편하게 만드는 방법을 간단히 정리한 글이다.
Unity Hpbar 만들기 개요
3D 게임에서 여러 몬스터 위에 동시에 편하게 추가 하는 방법에 대한 글이다.
- 캐릭터 머리 위에 이미지 표시 방법
- 체력에 따른 적용
- 응용
캐릭터 위에 이미지 표시하기
여기 3분간의 짧은 강좌를 보면서 작업했다.
- 캐릭터 prefab에 tag 설정
- 설정된 tag로 object들을 찾아옴
- 캐릭터 마다 hpbar object 생성(Instantiate)
- 매 프레임마다 생성된 hpbar 위치 update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HpBarScript : MonoBehaviour
{
[SerializeField] GameObject prefab = null;
List<Transform> objectList = new List<Transform>();
List<GameObject> hpBarList = new List<GameObject>();
Camera cam = null;
void Start()
{
cam = Camera.main;
GameObject[] t_objects = GameObject.FindGameObjectsWithTag(TagConstants.TAG_CAT);
for (int i = 0; i < t_objects.Length; i++)
{
objectList.Add(t_objects[i].transform);
GameObject hpBar = Instantiate(prefab, t_objects[i].transform.position, Quaternion.identity, transform);
hpBarList.Add(hpBar);
}
}
void Update()
{
for (int i = 0; i < objectList.Count; i++)
{
hpBarList[i].transform.position = cam.WorldToScreenPoint(objectList[i].transform.position + new Vector3(0, 5.15f, 0));
}
}
}
Hpbar 체력에 따라 이미지 사이즈 조절
- 위 동영상에서 제작한 hpbar를 기준으로 작업했다
- hpbar의 이미지의 scale을 체력의 비율에(current/max) 따라 조절
- 이미지의 피벗등의 셋팅은 여기를 참조 했다.
public class HpBar : MonoBehaviour
{
public GameObject innerBar;
public void updateHpbar(Vector3 pos, float current, float max)
{
transform.position = pos;
innerBar.transform.localScale = new Vector3(current / max, 1.0f, 1.0f);
}
}
내 게임에 실제 적용 시 (응용)
- GameManager에 모든 유닛들의 object를 등록
- 해당 object들을 참조해서 Hpbar를 유닛의 object에 각각 만든다. (유닛이 죽을 때 컨트롤 하기 쉽게)
- 모든 구조를 설명하기 어려워 달라진 부분만 코드로 남긴다.
void updateEnemys()
{
List<GameObject> characters = GameManager.sInstance.enemyContainer.enemys;
foreach (GameObject c in characters)
{
CharacterBase characterBase = c.GetComponent<CharacterBase>();
if (characterBase.hpBar == null)
{
characterBase.hpBar = createHpbar(c.transform.position);
}
HpBar hpbar = characterBase.hpBar.GetComponent<HpBar>();
if (hpbar != null)
{
hpbar.updateHpbar(cam.WorldToScreenPoint(characterBase.getHpBarPosition()), characterBase.Hp, characterBase.MaxHp);
}
}
}
GameObject createHpbar(Vector3 characterPosition)
{
return Instantiate(prefab, characterPosition, Quaternion.identity, transform);
}
🔔 포스팅 공지
ㅁㅇㄴㄻㄴㅇ