본문 바로가기
Unity 포트폴리오/플젝2. 3D FPS게임

Unity C# PlayerPrefs로 life이미지 관리하기

by jjiing 2022. 6. 21.

(본 글은 프로젝트 중 공부했던 내용을 개인적으로 기록하기 위한 용도입니다.)

 

PlayerPrefs

 

유니티에서 제공해주는 데이터 관리 클래스로, 보통은 초반에 유저의 정보를 받아 저장하는데 많이 쓰는 걸로 알고 있다.

나는 현재 라이프의 개수를 PlayerPrefs로 저장해 개수만큼 하트 이미지를 띄워주게끔 관리했다.

 

PlayerPrefs는 SetIntGetInt로 정수값을 설정하고 불러올 수 있다 (정수형 예시임)

 

PlayerPrefs.SetInt("lifeNum",GameManager.Instance.Life);

"lifeNum"이라는 변수에 게임매니저에서 라이프 개수를 불러와 설정해주고

PlayerPrefs.GetInt("lifeNum")으로 불러와 쓸 수 있다.

 

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

public class LifeImageControl : MonoBehaviour
{
    Image[] lifes;  //라이프 이미지 배열
    public GameObject lifesOn;


    //모드에 따라 라이프 개수 관리
    public enum Type { MODE1_1, MODE1_2 }; 
    public Type enumType;

    private void Start()
    {
        //자식 오브젝트에서 라이프 이미지 불러와 배열에 넣기
        lifes = lifesOn.GetComponentsInChildren<Image>();
        
    }
    private void Update()
    {
        //모드1 일 경우에는 라이프 3개, 모드 2는 라이프 1개라서 구분해서 각각 넣어줌.
        switch (enumType)
        {
            case Type.MODE1_1:
                PlayerPrefs.SetInt("lifeNum", GameManager.Instance.Life);
                for (int i = 0; i < 3 - PlayerPrefs.GetInt("lifeNum"); i++)
                {
                    lifes[i].gameObject.SetActive(false);
                }


                break;
            case Type.MODE1_2:
                PlayerPrefs.SetInt("lifeNum", GameManager.Instance.Life);
                for (int i = 0; i < 1 - PlayerPrefs.GetInt("lifeNum"); i++)
                {
                    lifes[i].gameObject.SetActive(false);
                }
                break;
            default:
                break;
        }

    }
}

 

3-"lifeNum"을 통해 줄어든 목숨 개수만큼 하트 이미지를 비활성화 해준다.

 

 

 

 

 

유니티창)

하이라키창
인스펙터창

LifeOn의 자식 이미지들을 불러옴

 

 

 

결과)