유니티 심화

SaveAndLoad - 캐릭터 프리팹 인스턴스화하기

다모아 2023. 9. 1. 14:41

https://jsonviewer.stack.hu/

 

Online JSON Viewer

 

jsonviewer.stack.hu

https://shancarter.github.io/mr-data-converter/

 

Mr. Data Converter

 

shancarter.github.io


App

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

public class App : MonoBehaviour
{
    //프리팹이 저장될 변수
    private List<GameObject> prefabs = new List<GameObject>();

    [SerializeField]
    private Button alienBtn;
    [SerializeField]
    private Button bearBtn;
    [SerializeField]
    private Button chemicalmanBtn;
    [SerializeField]
    private Button hoodieBtn;
    [SerializeField]
    private Button soldierBtn;

    [SerializeField]
    private List<GameObject> heroPrefabs = new List<GameObject>();

    private bool IsSpawn = false;
    private void Start()
    {
        //데이터 로드
       DataManager.instance.LoadHeroData();

        //프리팹 리소스 로드
        this.LoadPrefabs();

        alienBtn.onClick.AddListener(() =>
        {
            if(!IsSpawn)
            {
                Instantiate(this.heroPrefabs[0]);
                this.IsSpawn = true;
            }
            else
            {
                Debug.Log("더 이상 생성할 수 없습니다.");
            }
        });
        bearBtn.onClick.AddListener(() =>
        {
            if(!IsSpawn)
            {
                Instantiate(this.heroPrefabs[1]);
                this.IsSpawn = true;
            }
            else
            {
                Debug.Log("더 이상 생성할 수 없습니다.");
            }
        });
        chemicalmanBtn.onClick.AddListener(() =>
        {
            if(!IsSpawn)
            {
                Instantiate(this.heroPrefabs[2]);
                this.IsSpawn = true;
            }
            else
            {
                Debug.Log("더 이상 생성할 수 없습니다.");
            }
        });
        hoodieBtn.onClick.AddListener(() =>
        {
            if(!IsSpawn)
            {
                Instantiate(this.heroPrefabs[3]);
                this.IsSpawn = true;
            }
            else
            {
                Debug.Log("더 이상 생성할 수 없습니다.");
            }
        });
        soldierBtn.onClick.AddListener(() =>
        {
            if(!IsSpawn)
            {
                Instantiate(this.heroPrefabs[4]);
                this.IsSpawn = true;
            }
            else
            {
                Debug.Log("더 이상 생성할 수 없습니다.");
            }
        });
    }

    private void LoadPrefabs()
    {
        List<string> heroPrefabNames = DataManager.instance.GetHeroPrefabNames();

        foreach(string prefabName in heroPrefabNames)
        {
            string path = string.Format("Prefabs/{0}", prefabName);
            Debug.Log(path);
            GameObject prefab = Resources.Load<GameObject>(path);
            this.prefabs.Add(prefab);
            Debug.LogFormat("프리팹들이 로드 되었습니다. count: {0}", this.prefabs.Count);
        }
    }
}

 

DataManager

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataManager
{
    public static readonly DataManager instance = new DataManager();

    private Dictionary<int, HeroData> dicHeroDatas = new Dictionary<int, HeroData>();

    //생성자
    private DataManager()
    {

    }

    public void LoadHeroData()
    {
        TextAsset asset = Resources.Load<TextAsset>("Data/hero_data");
        Debug.Log(asset.text); //json 문자열

        //역직렬화
        HeroData[] heroDatas = JsonConvert.DeserializeObject<HeroData[]>(asset.text);
        foreach (HeroData data in heroDatas)
        {
            Debug.LogFormat("{0}, {1}, {2}, {3}, {4}, {5}", data.id, data.name, data.max_hp, data.damage, data.prefab_name, data.sprite_name);
            this.dicHeroDatas.Add(data.id, data); // 사전에 추가
        }

        Debug.LogFormat("<color=yellow>HeroData 로드 완료 : {0}</color>", this.dicHeroDatas.Count);
    }

    public List<string> GetHeroPrefabNames()
    {
        List<string> list = new List<string>();
         foreach(HeroData data in this.dicHeroDatas.Values)
        {
            list.Add(data.prefab_name);
        }
        return list;
    }
}

 

HeroData

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

public class HeroData
{
    public int id;
    public string name;
    public float max_hp;
    public float damage;
    public string prefab_name;
    public string sprite_name;

}

 

HeroInfo

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

public class HeroInfo
{
    public int id;
    public float hp;
    public float damage;

    //생성자
    public HeroInfo(int id, float hp, float damage)
    {
        this.id = id;
        this.hp = hp;
        this.damage = damage;
    }
}

뭔가 내가 한 방법이 잘못된것같다..라는게 느껴졌다.

나중에 다시 한번 해봐야할듯

'유니티 심화' 카테고리의 다른 글

LearnUGUI  (0) 2023.09.04
SaveAndLoad - UISlot  (0) 2023.09.01
SaveAndLoad  (0) 2023.09.01
조이스틱 인식오류  (0) 2023.09.01
HeroShooter - WASD /input Action  (0) 2023.08.31