using UnityEngine;
public class Zoo : MonoBehaviour
{
void Start()
{
ZooManager.Instance.LoadData(); // 데이터 로드
foreach (var animal in ZooManager.Instance.dicDatas.Values)
{
Debug.Log(animal.GetType().Name); // 클래스 이름 출력
}
}
}
Zoo.cs
using UnityEngine;
using Newtonsoft.Json;
using System.Collections.Generic;
public class ZooManager
{
public static readonly ZooManager Instance = new ZooManager();
public Dictionary<string, AnimalInfo> dicDatas = new Dictionary<string, AnimalInfo>();
private ZooManager() { }
public void LoadData()
{
var asset = Resources.Load<TextAsset>("zoo_info");
var json = asset.text;
var animalConverter = new JsonSerializerSettings();
animalConverter.Converters.Add(new AnimalInfoConverter());
var zooData = JsonConvert.DeserializeObject<ZooData>(json, animalConverter);
foreach (var data in zooData.animalInfos)
{
dicDatas.Add(data.name, data);
}
Debug.Log($"Data Load Complete! => Count : {dicDatas.Count}");
}
private class ZooData
{
public List<AnimalInfo> animalInfos { get; set; }
}
}
ZooManager.cs
(JSON 데이터가 배열 대신에 객체로 되어 있어서 역직렬화를 위해 ZooData 클래스를 정의)
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
public class AnimalInfoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(AnimalInfo));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
switch (jo["type"].Value<int>())
{
case 0:
return jo.ToObject<HerbivoreInfo>(serializer);
case 1:
return jo.ToObject<CarnivoreInfo>(serializer);
default:
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
return;
}
}
AnimalInfoConverter.cs
using UnityEngine;
public abstract class AnimalInfo
{
public string name;
public int moveSpeed;
public int type;
protected AnimalInfo(string name, int moveSpeed, int type)
{
this.name = name;
this.moveSpeed = moveSpeed;
this.type = type;
}
}
AnimalInfos.cs
using UnityEngine;
public class HerbivoreInfo : AnimalInfo
{
public int photosynthesis;
public HerbivoreInfo(string name, int moveSpeed, int photosynthesis) : base(name, moveSpeed, 0)
{
this.photosynthesis = photosynthesis;
}
}
HerbivoreInfo.cs
using UnityEngine;
public class CarnivoreInfo : AnimalInfo
{
public int damage;
public CarnivoreInfo(string name, int moveSpeed, int damage) : base(name, moveSpeed, 1)
{
this.damage = damage;
}
}
CarnivoreInfo.cs
'산대특 > 게임 알고리즘' 카테고리의 다른 글
울타리(fence)에 동물(animal)을 넣고 로그(Log)로 출력해보기 (0) | 2024.02.28 |
---|---|
메멘토 패턴(Memento Pattern) (0) | 2024.02.27 |
직렬화(Serialization)와 역직렬화(Deserialization) (0) | 2024.02.05 |
동기(Synchronous)와 비동기(Asynchronous) (0) | 2024.02.05 |
디자인 패턴 (0) | 2024.02.05 |