Unity ScripableObject => CSV
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
public class CSVExporter : ScriptableWizard
{
public string _ScriptableObjectClassName = "";
private string _SaveTo = "";
public string SaveTo
{
get
{
return _SaveTo;
}
private set
{
_SaveTo = value;
}
}
private Type type = null;
[MenuItem("Tools/Excel Config/Export Excel Template")]
static void ExportXml()
{
ScriptableWizard.DisplayWizard<CSVExporter>("Export Excel Template", "Export", "SelectPath");
}
void OnWizardUpdate()
{
isValid = false;
if (_ScriptableObjectClassName == "")
{
errorString = "Enter ScriptableObject class name";
return;
}
type = Type.GetType(_ScriptableObjectClassName);
if (type == null)
{
errorString = "Invalid class name!";
return;
}
isValid = true;
if (SaveTo == "")
{
errorString = "Select save path!";
return;
}
errorString = " ";
}
void OnWizardCreate()
{
ExportCSVMethod(_ScriptableObjectClassName, SaveTo, _ScriptableObjectClassName);
}
void OnWizardOtherButton()
{
SaveTo = EditorUtility.OpenFolderPanel("SaveTo", "", "") + "/";
if (SaveTo != "")
{
helpString = "SavePath: \"" + SaveTo + "\"";
return;
}
}
public void ExportCSVMethod(string typeName, string path, string fileName)
{
Type type = Type.GetType(typeName);
string filePath = path + fileName + ".csv";
string content = string.Empty;
using (StreamWriter sw = new StreamWriter(filePath))
{
FieldInfo[] fieldInfos = type.GetFields();
int count = 0;
foreach (FieldInfo fieldInfo in fieldInfos)
{
if (!fieldInfo.IsNotSerialized)
{
if (count > 0)
{
sw.Write(',');
}
sw.Write(fieldInfo.Name);
count++;
}
}
}
}
}
CSV=>Excel Excel=>CSV 别忘了改成UTF格式,否则读不了中文!!!
CSV => Unity ScripableObject
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class CSVImporter
{
[MenuItem("Tools/Excel Config/Import Excel Data")]
public static void ImportXmlTemplateMethod()
{
DirectoryInfo info = new DirectoryInfo("Assets");
if (!info.Exists) info.Create();
string path = EditorUtility.OpenFilePanel("Import Excel Data", "", "csv");
if (string.IsNullOrEmpty(path))
return;
string[] split = path.Split('/');
string fileName = split[split.Length - 1].Split('.')[0];
string copyPath = "Assets/" + fileName + ".csv";
TextAsset text = AssetDatabase.LoadMainAssetAtPath(copyPath) as TextAsset;
if (text != null)
{
AssetDatabase.DeleteAsset(copyPath);
}
FileUtil.CopyFileOrDirectory(path, Application.dataPath + "/" + fileName + ".csv");
AssetDatabase.ImportAsset(copyPath);
text = AssetDatabase.LoadMainAssetAtPath(copyPath) as TextAsset;
if (text == null)
{
return;
}
Type dataType = Type.GetType(fileName);
if (dataType == null)
{
AssetDatabase.DeleteAsset(copyPath);
Debug.Log("Don't hava this name of ScriptableObject:" + fileName);
return;
}
string importPath = EditorUtility.SaveFilePanel("Save Data Path", Application.dataPath, "data", ".asset");
if (string.IsNullOrEmpty(importPath))
return;
string relativePath = importPath.Split(new string[] { "Assets" }, StringSplitOptions.None)[1];
string[] divides = relativePath.Split('/');
string saveFolder = "Assets";
for (int i = 0; i < divides.Length - 1; i++)
{
saveFolder += divides[i] + "/";
}
string[] rows = text.text.Split(new string[] { "\n" }, System.StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < rows.Length; i++)
{
rows[i] = rows[i].TrimEnd('\r');
}
string[] columns = rows[0].Split(',');
List<FieldInfo> fieldInfos = new List<FieldInfo>();
List<bool> multis = new List<bool>();
foreach (string column in columns)
{
string col = column.TrimEnd();
string fieldName = col.Split('+')[0];
FieldInfo field = dataType.GetField(fieldName);
if (field != null)
{
fieldInfos.Add(field);
bool multi = col.Contains("+");
multis.Add(multi);
}
else
{
Debug.Log(fieldName);
}
}
for (int i = 1; i < rows.Length; i++)
{
if (rows[i] == null)
continue;
columns = rows[i].Split(',');
string assetPath = saveFolder + columns[0] + ".asset";
ScriptableObject asset = ScriptableObject.CreateInstance(fileName);
for (int j = 0; j < fieldInfos.Count; j++)
{
object value = StringConvert.ToValue(fieldInfos[j].FieldType, columns[j], multis[j]);
fieldInfos[j].SetValue(asset, value);
}
AssetDatabase.CreateAsset(asset, assetPath);
AssetDatabase.ImportAsset(assetPath);
AssetDatabase.Refresh();
}
AssetDatabase.DeleteAsset(copyPath);
}
}
字符串类型转为其他类型:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = System.Object;
public class StringConvert
{
public static Object ToValue(Type type, string s, bool multi)
{
object o = null;
s = ClearEndEmpty(s);
if (type.IsEnum)
{
if (multi)
{
int value = 0;
if (s == "无")
{
value = 0;
}
else
{
string[] currentEnumNames = s.Split('+');
for (int i = 0; i < currentEnumNames.Length; i++)
{
value += (int)Enum.Parse(type, currentEnumNames[i]);
}
o = value;
}
o = value;
}
else
{
o = Enum.Parse(type, s);
}
}
else if (typeof(string).Equals(type))
{
o = s;
}
else if (typeof(bool).Equals(type))
{
o = s.Equals("1");
}
else if (typeof(int).Equals(type))
{
int value = 0;
int.TryParse(s, out value);
o = value;
}
else if (typeof(float).Equals(type))
{
float value = 0f;
float.TryParse(s, out value);
o = value;
}
return o;
}
public static string ClearEndEmpty(string s)
{
return s.TrimEnd(new char[] {' ', '\r', '\n' });
}
}
|