CapersProject/Assets/02.Scripts/Item/ItemDropTableSo.cs
2024-08-22 19:39:15 +09:00

89 lines
3.5 KiB
C#

using System.Collections.Generic;
using System.IO;
using BlueWater.Items;
using Newtonsoft.Json.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace BlueWater.Items
{
public class ItemDropTableSo : ScriptableObject
{
// public 필수
public List<ItemDropTable> ItemDropTables = new();
private const string ItemDropJsonPath = "Assets/Resources/Json/ItemDropTable.json";
private const string CharacterDataJsonPath = "Assets/Resources/Json/CharacterData.json";
private const string FilePath = "Assets/02.Scripts/ScriptableObject/Item/ItemDropTable.asset";
#if UNITY_EDITOR
[MenuItem("Tools/ItemDropTable ScriptableObject 생성")]
private static void CreateItemDropTable()
{
var itemDropJsonContent = File.ReadAllText(ItemDropJsonPath);
var characterDataJsonContent = File.ReadAllText(CharacterDataJsonPath);
var instance = CreateFromJson(itemDropJsonContent, characterDataJsonContent);
AssetDatabase.CreateAsset(instance, FilePath);
AssetDatabase.SaveAssets();
Debug.Log("ItemDropTable ScriptableObject created successfully in ItemDropTableScriptableObject class.");
}
#endif
private static ItemDropTableSo CreateFromJson(string itemDropJsonString, string characterDataJsonString)
{
var itemDropTables = ParseJsonToCharacterDrops(itemDropJsonString, characterDataJsonString);
var instance = CreateInstance<ItemDropTableSo>();
instance.ItemDropTables = itemDropTables;
return instance;
}
private static List<ItemDropTable> ParseJsonToCharacterDrops(string itemDropJsonString, string characterDataJsonString)
{
var newItemDropTables = new List<ItemDropTable>();
var itemDropTables = new Dictionary<string, ItemDropTable>();
var characterDataDictionary = ParseCharacterDataJson(characterDataJsonString);
var jsonArray = JArray.Parse(itemDropJsonString);
foreach (var element in jsonArray)
{
var characterIdx = (string)element["CharacterIdx"];
var dropItem = new DropItem
{
ItemIdx = (string)element["ItemIdx"],
DropRate = (int)element["DropRate"],
QuantityMin = (int)element["QuantityMin"],
QuantityMax = (int)element["QuantityMax"]
};
if (!itemDropTables.ContainsKey(characterIdx))
{
var characterName = characterDataDictionary.GetValueOrDefault(characterIdx, "Unknown");
itemDropTables[characterIdx] = new ItemDropTable(new CharacterData(characterIdx, characterName));
}
itemDropTables[characterIdx].DropItems.Add(dropItem);
}
newItemDropTables.AddRange(itemDropTables.Values);
return newItemDropTables;
}
private static Dictionary<string, string> ParseCharacterDataJson(string characterDataJsonString)
{
var characterDataDictionary = new Dictionary<string, string>();
var jsonArray = JArray.Parse(characterDataJsonString);
foreach (var element in jsonArray)
{
var characterIdx = (string)element["CharacterIdx"];
var name = (string)element["Name"];
characterDataDictionary[characterIdx] = name;
}
return characterDataDictionary;
}
}
}