본문 바로가기
Unity/수업 내용

[2D]프로젝트Play&plane - 생명력 표시(3개)

by 이지훈26 2021. 10. 14.

GameMain 오브젝트 생성

GameMain 스크립트 생성 후 오브젝트에 끌어다 넣기

 

GameMain 스크립트 코드 작성

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

public class GameMain : MonoBehaviour
{
    public int playerLife = 3;
    public GameDirector gameDirector;

    // Start is called before the first frame update
    void Start()
    {
        this.gameDirector.Init(this.playerLife);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


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

public class GameDirector : MonoBehaviour
{
    public Text txtScore;
    private int totalScore;
    public GameObject[] lifes;

    public void Init(int playerLife)
    {
        for (int i = 0; i < lifes.Length; i++)
            this.lifes[i].SetActive(false);

        for (int i = 0; i < playerLife; i++)
            this.lifes[i].SetActive(true);
    }
    public void AddScore(int score)
    {
        this.totalScore += score;
        this.txtScore.text = totalScore.ToString();
    }
}

 

 

 

Canvas 자식으로, UI -> Image 생성 후 Life 이미지를 넣어준다

왼쪽 상단에 두고 2개 더 복사하여 3개로 정렬해주기

 

 

 

GameDirector 오브젝트에 Lifes를 3으로 해주고 안에 각각 3개의 목숨을 넣어준다

 

 

GameMain 오브젝트에 PlayerLifes를 3으로 맞춰주고

GameDirector에 GameDirector오브젝트를 넣어준다