I have a requirement to automate the creation of X amount of scriptable objects from a CSV file, in the image below is an example of a manually completed one, the minimum amount of automation I need for this is the name/description/stat modifier.
The CSVtoSO class below successfully creates a SO with the name and description passed in as strings, the simple method that is called is in the base Inventoryitem class as below, the problem I have lies in the fact that I need to expose the class stat which is an enum and almost cast this as a string read in from the CSV
Ive dropped the statsEquippableItem Class at the bottom and within here I think I need an equivalent setter method but almost passing a string as the argument cast as the stats class which I dont think is possible, hopefully I have explained this post well enough, any tips would be great !
public enum Stat
{
Mana,
Stamina,
Spirit,
Intellect,
Strength,
Agility
}
This method lives in InventoryItem
public void SetDescription(string Description)
{
this.description = Description;
}
using UnityEngine;
using UnityEditor;
using System.IO;
public class CSVToSO
{
private static string EquipCSVLocation = "/Inventories/TestItemCSV.csv";
[MenuItem("Utilities/generate equipment")]
public static void GenerateEquip()
{
string[] allLines = File.ReadAllLines(Application.dataPath EquipCSVLocation);
foreach (string s in allLines)
{
string[] splitData = s.Split(',');
StatsEquipableItem NewItem = ScriptableObject.CreateInstance<StatsEquipableItem>();
NewItem.SetDisplayName(splitData[0]);
NewItem.SetDescription(splitData[1]);
AssetDatabase.CreateAsset(NewItem,$"Assets/Game/EquippableItems/Resources/Rare/{NewItem.GetDisplayName()}.asset");
}
AssetDatabase.SaveAssets();
}
}
StatsEquipableItem Class
using System.Collections.Generic;
using UnityEngine;
public class StatsEquipableItem : EquipableItem, IModifierProvider
{
[SerializeField]
Modifier[] additiveModifiers;
[SerializeField]
Modifier[] percentageModifiers;
[System.Serializable]
struct Modifier
{
public Stat stat;
public float value;
}
public IEnumerable<float> GetAdditiveModifiers(Stat stat)
{
foreach (var modifier in additiveModifiers)
{
if (modifier.stat == stat)
{
yield return modifier.value;
}
}
}
public IEnumerable<float> GetPercentageModifiers(Stat stat)
{
foreach (var modifier in percentageModifiers)
{
if (modifier.stat == stat)
{
yield return modifier.value;
}
}
}
}
CodePudding user response:
I believe your question is "How do convert a string to an Enum value?". If so, enum has the Parse
and TryParse
methods which take in a string and attempt to convert it to the enum value.
if (System.Enum.TryParse(statStringValue, out Stat statValue))
{
Debug.Log($"Converted {statStringValue} to Stat value {statValue}");
}
else
{
Debug.Log($"Unable to convert {statStringValue} to Stat value");
}