유니티 목숨 UI 구현 (Unity Health UI)

농담고미고미·2024년 5월 24일

Unity 개발 일지

목록 보기
2/26

https://www.youtube.com/watch?v=GHUJMXtHKL0&t=2036s

Unity HEART/HEALTH SYSTEM - 2D Platformer

큰 순서 :
1. Prefabs에 LifeMinus 아이템을 추가한다. (우선은 LifeMinus를 먹으면 콘솔 창에 "목숨 -1" 글이 뜨도록 한다.)
2. Canvas에 HeartContainer로 하트 3개를 만든다. GameOverPanel도 만든다.
3. HealthManager 스크립트와 PlayerManager 스크립트를 생성해 코드를 작성한다. (HealthManger에서 목숨이 깎이면 이미지를 교체하도록 코드작성)

우선, Prefabs에 LifeMinus를 추가한다.

Canvas에 HeartContainer (목숨 이미지)와 목숨이 0개가 됐을 때 뜨는 GameOverPanel을 만든다.

HeartContainer는 Heart 이미지 3개를 연달아 붙인건데, Horizontal Layout Group을 이용하면 좀 더 편리하게 이미지 이동이 가능하다.

GameOverPanel은 평소에는 보이면 안되니깐 (목숨이 0개가 됐을 때만 보여야함) 체크를 꺼둡시다.

PlayerManager도 생성해줍시다.

HealthManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthManager : MonoBehaviour
{
    public static int health = 3;

    public Image[] hearts;
    public Sprite fullHeart;
    public Sprite emptyHeart;

    // Update is called once per frame
    void Update()
    {
        foreach (Image img in hearts)
        {
            img.sprite = emptyHeart;
        }
        for (int i = 0; i < health; i++)
        {
            hearts[i].sprite = fullHeart;
        }
    }
}

itemManager

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

public class ItemManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Coin"))
        {
            Debug.Log("코인 +1");
        }

        else if (collision.gameObject.CompareTag("LifePlus"))
        {
            Debug.Log("목숨 +1");
        }

        else if (collision.gameObject.CompareTag("ScoreMinus"))
        {
            Debug.Log("점수 -1");
        }

        else if (collision.gameObject.CompareTag("LifeMinus"))
        {
            HealthManager.health--;
            if(HealthManager.health <= 0 )
            {
                PlayerManager.isGameOver = true;
                gameObject.SetActive(false);
            }
        }
        Destroy(collision.gameObject);
    }
}

PlayeManager

using UnityEngine.SceneManagement;
using UnityEngine;

public class PlayerManager : MonoBehaviour
{
    public static bool isGameOver;
    public GameObject gameOverScreen;
    private void Awake()
    {
        isGameOver = false;
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (isGameOver)
        {
            gameOverScreen.SetActive(true);
        }
    }
}
profile
농담곰을 좋아해요 말랑곰탱이

0개의 댓글