Unity

3D 테스트 프로젝트 7

psb08 2025. 2. 28. 14:35
728x90

체력 시스템을 만들었습니다.

적이 한 번에 죽지 않게 하기 위해서도 있지만, 플레이어를 위해서도 있습니다.

 

HpSystem.cs

using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

public class HpSystem : MonoBehaviour
{
    [Header("체력 설정")]
    public float maxHealth = 100f;
    public float currentHealth;

    public event Action<float, float> OnHealthChanged;
    public UnityEvent OnDeath;

    private void Awake()
    {
        currentHealth = maxHealth;
    }

    // 데미지를 받는 메서드
    public void TakeDamage(float amount)
    {
        if (currentHealth <= 0) return; // 이미 죽었으면 실행 X

        currentHealth -= amount;
        currentHealth = Mathf.Clamp(currentHealth, 0, maxHealth); // 체력 0~최대값 유지
        OnHealthChanged?.Invoke(currentHealth, maxHealth); // 체력 변경 이벤트 실행

        if (currentHealth <= 0)
        {
            Die();
        }
    }

    // 체력을 회복하는 메서드
    public void Heal(float amount)
    {
        if (currentHealth <= 0) return; // 죽은 상태에서는 회복 불가

        currentHealth += amount;
        currentHealth = Mathf.Clamp(currentHealth, 0, maxHealth);
        OnHealthChanged?.Invoke(currentHealth, maxHealth);
    }

    // 사망 처리 메서드
    private void Die()
    {
        if (gameObject.name.Contains("Player"))
        {
            SceneManager.LoadScene(0);
        }
        if (gameObject.name.Contains("Enemy"))
        {
            Destroy(gameObject);
        }
        OnDeath?.Invoke(); // 사망 이벤트 실행
    }

    // 현재 체력 반환
    public float GetHealth()
    {
        return currentHealth;
    }

}

인스펙터에서  최대체력과 현재체력을 볼 수 있게 했습니다.

 

체력이 바뀌었을 때 할 수 있는 이벤트와 죽었을 때 실행할 수 있는 이벤트를 만들었습니다.

TakeDamage 메서드는 자신에게 데미지를 줍니다.

Heal 메서드는 자신의 체력을 회복할 수 있습니다.

 

Die에서는 Player가 죽으면 씬을 옮기고, Enemy가 죽으면 오브젝트를 파괴합니다.

 

GetHealth는 체력을 반환합니다만 아직 사용한 곳은 없습니다.

 

HpText.cs

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

public class HpText : MonoBehaviour
{
    public HpSystem hpSystem;
    public TextMeshProUGUI hpText;

    private void Update()
    {
        hpText.text = $"HP : {hpSystem.currentHealth.ToString("F0")}";
    }

}

이 스크립트는 플레이어의 체력을 UI로 띄우기 위해 만들었습니다.

 

 

 

영상을 보시면 적에게 닿으면 체력이 20 닳게 되며, 저번에 만든 Shield를 사용 시, 체력이 점차 차는 모습을 볼 수 있습니다. 체력이 0이 되면 씬을 옮깁니다.

728x90

'Unity' 카테고리의 다른 글

3D 테스트 프로젝트 9  (0) 2025.03.02
3D 테스트 프로젝트 8  (0) 2025.03.01
3D 테스트 프로젝트 6  (0) 2025.02.27
3D 테스트 프로젝트 5  (0) 2025.02.26
3D 테스트 프로젝트 4  (0) 2025.02.25