当前位置:网站首页>[unity] upgraded version · Excel data analysis, automatically create corresponding C classes, automatically create scriptableobject generation classes, and automatically serialize asset files

[unity] upgraded version · Excel data analysis, automatically create corresponding C classes, automatically create scriptableobject generation classes, and automatically serialize asset files

2022-07-06 22:50:00 InfoQ

Realization function :

  • Automatically create inheritance ScriptableObject Of C# Data class , Every one of them Excel The data of , Have corresponding fields Get function ; 



  • Automatically create each Excel Of Asset Generate classes and generate functions , Used to automatically generate Asset file
null
  • use Asset Automatic serialization of generated classes Excel Data to Asset file , It can be loaded and used directly when the project is running

Realization principle :

Excel Configuration format :

  • The first 1 Lines correspond to special marks ( Validity can be set , Specify the file to create )
  • The first 2 The line corresponds to the Chinese description ( As a first 3 Comments for line fields )
  • The first 3 Row corresponding field name ( Automatically created field name )
  • The first 4 The row corresponds to the field type ( Automatically created field types , One to one correspondence with field name )
  • The first 5 Row and subsequent corresponding field values ( All the data , Analyze in behavioral units 、 Save the data )
  • The fixed fields in the first column are "id", Is the index of each line of data in the code Key
Excel Annotation operations :
  • Field name line , Add "//", You can annotate this field , Will not parse to C# class ;
  • Add "//", You can annotate a line of data , It won't be saved to Asset In file ;
  • Comments can be used to add a description line , Or eliminate the specified useless data .

Generated C# Class format :

Row data class , Corresponding to each row of data :
[Serializable]
public class TestConfigExcelItem : ExcelItemBase
{
/// <summary>
///  data id
/// </summary>>
public int id;
/// <summary>
///  character string
/// </summary>>
public string testString;
/// <summary>
/// Int
/// </summary>>
public int testInt;
/// <summary>
/// Float
/// </summary>>
public float testFloat;
}

Complete data class , Contains all rows of data 、 Initialization function 、Get function :
public class TestConfigExcelData : ExcelDataBase<TestConfigExcelItem>
{
public TestConfigExcelItem[] items;

public Dictionary<int,TestConfigExcelItem> itemDic = new Dictionary<int,TestConfigExcelItem>();

public void Init()
{
itemDic.Clear();
if(items != null && items.Length > 0)
{
for(int i = 0; i < items.Length; i++)
{
itemDic.Add(items[i].id, items[i]);
}
}
}

public TestConfigExcelItem GetTestConfigExcelItem(int id)
{
if(itemDic.ContainsKey(id))
return itemDic[id];
else
return null;
}
#region --- Get Method ---

public string GetTestString(int id)
{
var item = GetTestConfigExcelItem(id);
if(item == null)
return default;
return item.testString;
}

// ··· ···

#endregion
}

Currently supported data structures :

because Unity Cannot serialize a two-dimensional array , Here it is changed to a one-dimensional array + Structure is realized :
[Serializable]
public struct StringArr
{
 public string[] array;
}

// Two dimensional array representation : StringArr[]

Asset Data files :

In the process of automatically generating data C# Class time , Will be generated synchronously Asset File creation class , For automatic creation of Asset File and serialize data .

null

advantage :

  • After data modification, you only need to regenerate with one click
  • Every Excel Corresponding to a class , Flexible use , Yes Excel Less restrictions
  • Automatically create C# class , There is no need for each Excel Write code manually , Each data corresponds to a field , There is no need to unpack and decorate
  • Automatically create ScriptableObject Of Asset file , Automatically serialize data , Convenient view , You can manually modify and adjust , There is no need to change every time Excel In the operation
  • Read directly in the game Asset Of ScriptableObject Subclass , No need for extra operation , The business layer directly accesses data fields

Usage method :

  • Configure in standard format Excel
  • One click generation C# class 、Asset file
  • The project runtime loads Asset resources , call Init initialization ,Get Function to get the corresponding field value


Complete code :

Expand Unity Editor window :

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Linq;

public class BuildExcelWindow : EditorWindow
{
 [MenuItem(&quot;MyTools/Excel Window&quot;,priority = 100)]
 public static void ShowReadExcelWindow()
 {
 BuildExcelWindow window = GetWindow<BuildExcelWindow>(true);
 window.Show();
 window.minSize = new Vector2(475,475);
 }

 //Excel Read path , Absolute path , Put it in Assets Peer path
 private static string excelReadAbsolutePath;

 // Automatic generation C# Class file path , Absolute path
 private static string scriptSaveAbsolutePath;
 private static string scriptSaveRelativePath;
 // Automatic generation Asset File path , Relative paths
 private static string assetSaveRelativePath;

 private List<string> fileNameList = new List<string>();
 private List<string> filePathList = new List<string>();

 private void Awake()
 {
 titleContent.text = &quot;Excel Configuration table read &quot;;

 excelReadAbsolutePath = Application.dataPath.Replace(&quot;Assets&quot;,&quot;Excel&quot;);
 scriptSaveAbsolutePath = Application.dataPath + CheckEditorPath(&quot;/Script/Excel/AutoCreateCSCode&quot;);
 scriptSaveRelativePath = CheckEditorPath(&quot;Assets/Script/Excel/AutoCreateCSCode&quot;);
 assetSaveRelativePath = CheckEditorPath(&quot;Assets/AssetData/Excel/AutoCreateAsset&quot;);
 }

 private void OnEnable()
 {
 RefreshExcelFile();
 }

 private void OnDisable()
 {
 fileNameList.Clear();
 filePathList.Clear();
 }

 private Vector2 scrollPosition = Vector2.zero;
 private void OnGUI()
 {
 GUILayout.Space(10);

 scrollPosition = GUILayout.BeginScrollView(scrollPosition,GUILayout.Width(position.width),GUILayout.Height(position.height));

 // Show the way
 GUILayout.BeginHorizontal(GUILayout.Height(20));
 if(GUILayout.Button(&quot;Excel Read path &quot;,GUILayout.Width(100)))
 {
 EditorUtility.OpenWithDefaultApp(excelReadAbsolutePath);
 Debug.Log(excelReadAbsolutePath);
 }
 if(GUILayout.Button(&quot;Script Save the path &quot;,GUILayout.Width(100)))
 {
 SelectObject(scriptSaveRelativePath);
 }
 if(GUILayout.Button(&quot;Asset Save the path &quot;,GUILayout.Width(100)))
 {
 SelectObject(assetSaveRelativePath);
 }
 GUILayout.EndHorizontal();

 GUILayout.Space(5);

 //Excel list

 GUILayout.Label(&quot;Excel list :&quot;);
 for(int i = 0; i < fileNameList.Count; i++)
 {
 GUILayout.BeginHorizontal(&quot;Box&quot;,GUILayout.Height(40));

 GUILayout.Label($&quot;{i}:&quot;,&quot;Titlebar Foldout&quot;,GUILayout.Width(30),GUILayout.Height(35));
 GUILayout.Box(fileNameList[i],&quot;MeTransitionBlock&quot;,GUILayout.MinWidth(200),GUILayout.Height(35));
 GUILayout.Space(10);

 // Generate CS Code
 if(GUILayout.Button(&quot;Create Script&quot;,GUILayout.Width(100),GUILayout.Height(30)))
 {
 ExcelDataReader.ReadOneExcelToCode(filePathList[i],scriptSaveAbsolutePath);
 }
 // Generate Asset file
 if(GUILayout.Button(&quot;Create Asset&quot;,GUILayout.Width(100),GUILayout.Height(30)))
 {
 ExcelDataReader.CreateOneExcelAsset(filePathList[i],assetSaveRelativePath);
 }

 GUILayout.EndHorizontal();
 GUILayout.Space(5);
 }
 GUILayout.Space(10);

 // One click processing all Excel

 GUILayout.Label(&quot; One click operation :&quot;);
 GUILayout.BeginHorizontal(&quot;Box&quot;,GUILayout.Height(40));

 GUILayout.Label(&quot;all&quot;,&quot;Titlebar Foldout&quot;,GUILayout.Width(30),GUILayout.Height(35));
 GUILayout.Box(&quot;All Excel&quot;,&quot;MeTransitionBlock&quot;,GUILayout.MinWidth(200),GUILayout.Height(35));
 GUILayout.Space(10);

 if(GUILayout.Button(&quot;Create Script&quot;,GUILayout.Width(100),GUILayout.Height(30)))
 {
 ExcelDataReader.ReadAllExcelToCode(excelReadAbsolutePath,scriptSaveAbsolutePath);
 }
 if(GUILayout.Button(&quot;Create Asset&quot;,GUILayout.Width(100),GUILayout.Height(30)))
 {
 ExcelDataReader.CreateAllExcelAsset(excelReadAbsolutePath,assetSaveRelativePath);
 }
 GUILayout.EndHorizontal();

 //
 GUILayout.Space(20);
 //
 GUILayout.EndScrollView();
 }

 // Read the... Under the specified path Excel file name
 private void RefreshExcelFile()
 {
 fileNameList.Clear();
 filePathList.Clear();

 if(!Directory.Exists(excelReadAbsolutePath))
 {
 Debug.LogError(&quot; Invalid path :&quot; + excelReadAbsolutePath);
 return;
 }
 string[] excelFileFullPaths = Directory.GetFiles(excelReadAbsolutePath,&quot;*.xlsx&quot;);

 if(excelFileFullPaths == null || excelFileFullPaths.Length == 0)
 {
 Debug.LogError(excelReadAbsolutePath + &quot; Not found under path Excel file &quot;);
 return;
 }

 filePathList.AddRange(excelFileFullPaths);
 for(int i = 0; i < filePathList.Count; i++)
 {
 fileNameList.Add(Path.GetFileName(filePathList[i]));
 }
 Debug.Log(&quot; find Excel file :&quot; + fileNameList.Count + &quot; individual &quot;);
 }

 private void SelectObject(string targetPath)
 {
 Object targetObj = AssetDatabase.LoadAssetAtPath<Object>(targetPath);
 EditorGUIUtility.PingObject(targetObj);
 Selection.activeObject = targetObj;
 Debug.Log(targetPath);
 }

 private static string CheckEditorPath(string path)
 {
#if UNITY_EDITOR_WIN
 return path.Replace(&quot;/&quot;,&quot;\\&quot;);
#elif UNITY_EDITOR_OSX
 return path.Replace(&quot;\\&quot;,&quot;/&quot;);
#else
 return path;
#endif
 }
}

Excel Data reading class :&nbsp;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Excel;
using System.Reflection;
using System;
using System.Linq;

public class ExcelDataReader
{
 //Excel The first 1 Lines correspond to special marks
 private const int specialSignRow = 0;
 //Excel The first 2 The line corresponds to the Chinese description
 private const int excelNodeRow = 1;
 //Excel The first 3 Row corresponding field name
 private const int excelNameRow = 2;
 //Excel The first 4 The row corresponds to the field type
 private const int excelTypeRow = 3;
 //Excel The first 5 Row and subsequent corresponding field values
 private const int excelDataRow = 4;

 // Mark comment lines / Column
 private const string annotationSign = &quot;//&quot;;

 #region --- Read Excel ---

 // establish Excel Corresponding C# class
 public static void ReadAllExcelToCode(string allExcelPath,string codeSavePath)
 {
 // Read all Excel file
 // The full name of the file in the specified directory that matches the specified search pattern and options ( Inclusion path ) Array of ; If no files are found , Is an empty array .
 string[] excelFileFullPaths = Directory.GetFiles(allExcelPath,&quot;*.xlsx&quot;);
 if(excelFileFullPaths == null || excelFileFullPaths.Length == 0)
 {
 Debug.Log(&quot;Excel file count == 0&quot;);
 return;
 }
 // Traverse all of Excel, establish C# class
 for(int i = 0; i < excelFileFullPaths.Length; i++)
 {
 ReadOneExcelToCode(excelFileFullPaths[i],codeSavePath);
 }
 }

 // establish Excel Corresponding C# class
 public static void ReadOneExcelToCode(string excelFullPath,string codeSavePath)
 {
 // analysis Excel Get intermediate data
 ExcelMediumData excelMediumData = CreateClassCodeByExcelPath(excelFullPath);
 if(excelMediumData == null)
 {
 Debug.LogError($&quot; Read Excel Failure  : {excelFullPath}&quot;);
 return;
 }
 if(!excelMediumData.isValid)
 {
 Debug.LogError($&quot; Read Excel Failure ,Excel Mark failure  : {excelMediumData.excelName}&quot;);
 return;
 }

 if(!excelMediumData.isCreateCSharp && !excelMediumData.isCreateAssignment)
 {
 Debug.LogError($&quot; Read Excel Failure ,Excel Generation of CSCode : {excelMediumData.excelName}&quot;);
 return;
 }

 // Generate... From data C# Script
 string classCodeStr = ExcelCodeCreater.CreateCodeStrByExcelData(excelMediumData);
 if(string.IsNullOrEmpty(classCodeStr))
 {
 Debug.LogError($&quot; analysis Excel Failure  : {excelMediumData.excelName}&quot;);
 return;
 }

 // Check the export path
 if(!Directory.Exists(codeSavePath))
 Directory.CreateDirectory(codeSavePath);
 // Class name
 string codeFileName = excelMediumData.excelName + &quot;ExcelData&quot;;
 // Writing documents , Generate CS Class file
 StreamWriter sw = new StreamWriter($&quot;{codeSavePath}/{codeFileName}.cs&quot;);
 sw.WriteLine(classCodeStr);
 sw.Close();
 //
 UnityEditor.AssetDatabase.SaveAssets();
 UnityEditor.AssetDatabase.Refresh();
 //
 Debug.Log($&quot; Generate Excel Of CS success  : {excelMediumData.excelName}&quot;);
 }

 #endregion

 #region --- Create Asset ---

 // establish Excel Corresponding Asset Data files
 public static void CreateAllExcelAsset(string allExcelPath,string assetSavePath)
 {
 // Read all Excel file
 // The full name of the file in the specified directory that matches the specified search pattern and options ( Inclusion path ) Array of ; If no files are found , Is an empty array .
 string[] excelFileFullPaths = Directory.GetFiles(allExcelPath,&quot;*.xlsx&quot;);
 if(excelFileFullPaths == null || excelFileFullPaths.Length == 0)
 {
 Debug.Log(&quot;Excel file count == 0&quot;);
 return;
 }
 // Traverse all of Excel, establish Asset
 for(int i = 0; i < excelFileFullPaths.Length; i++)
 {
 CreateOneExcelAsset(excelFileFullPaths[i],assetSavePath);
 }
 }

 // establish Excel Corresponding Asset Data files
 public static void CreateOneExcelAsset(string excelFullPath,string assetSavePath)
 {
 // analysis Excel Get intermediate data
 ExcelMediumData excelMediumData = CreateClassCodeByExcelPath(excelFullPath);
 if(excelMediumData == null)
 {
 Debug.LogError($&quot; Read Excel Failure  : {excelFullPath}&quot;);
 return;
 }
 if(!excelMediumData.isValid)
 {
 Debug.LogError($&quot; Read Excel Failure ,Excel Mark failure  : {excelMediumData.excelName}&quot;);
 return;
 }

 if(!excelMediumData.isCreateAsset)
 {
 Debug.LogError($&quot; Read Excel Failure ,Excel Generation of Asset : {excelMediumData.excelName}&quot;);
 return;
 }

 //// Get the current assembly
 //Assembly assembly = Assembly.GetExecutingAssembly();
 //// Create an instance of a class , Return to  object  type , A cast is required ,assembly.CreateInstance(&quot; The fully qualified name of the class ( Including the namespace )&quot;);
 //object class0bj = assembly.CreateInstance(excelMediumData.excelName + &quot;Assignment&quot;,true);

 // You must traverse all assemblies to get the type . The current in Assembly-CSharp-Editor in , The target type is Assembly-CSharp in , Different programs will not be able to get types
 Type assignmentType = null;
 string assetAssignmentName = excelMediumData.excelName + &quot;AssetAssignment&quot;;
 foreach(var asm in AppDomain.CurrentDomain.GetAssemblies())
 {
 // Find the target type
 Type tempType = asm.GetType(assetAssignmentName);
 if(tempType != null)
 {
 assignmentType = tempType;
 break;
 }
 }
 if(assignmentType == null)
 {
 Debug.LogError($&quot; Creation boundary Asset Failure , Not found Asset Generating classes  : {excelMediumData.excelName}&quot;);
 return;
 }

 // Reflection acquisition method
 MethodInfo methodInfo = assignmentType.GetMethod(&quot;CreateAsset&quot;);
 if(methodInfo == null)
 {
 if(assignmentType == null)
 {
 Debug.LogError($&quot; Creation boundary Asset Failure , Not found Asset Create a function  : {excelMediumData.excelName}&quot;);
 return;
 }
 }

 methodInfo.Invoke(null,new object[] { excelMediumData,assetSavePath });
 // establish Asset File successfully
 Debug.Log($&quot; Generate Excel Of Asset success  : {excelMediumData.excelName}&quot;);
 }

 #endregion

 #region --- private ---

 // analysis Excel, Create intermediate data
 private static ExcelMediumData CreateClassCodeByExcelPath(string excelFileFullPath)
 {
 if(string.IsNullOrEmpty(excelFileFullPath))
 return null;

 excelFileFullPath = excelFileFullPath.Replace(&quot;\\&quot;,&quot;/&quot;);
 // Read Excel
 FileStream stream = File.Open(excelFileFullPath,FileMode.Open,FileAccess.Read);
 if(stream == null)
 return null;
 // analysis Excel
 IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
 // Invalid Excel
 if(excelReader == null || !excelReader.IsValid)
 {
 Debug.Log(&quot;Invalid excel : &quot; + excelFileFullPath);
 return null;
 }

 Debug.Log(&quot; Start parsing Excel : &quot; + excelReader.Name);

 // Record Excel data
 ExcelMediumData excelMediumData = new ExcelMediumData();

 //Excel name
 excelMediumData.excelName = excelReader.Name;

 // Currently traversed rows
 int curRowIndex = 0;
 // Start reading , Go through... By line
 while(excelReader.Read())
 {
 // No data is read in this line , Treat as invalid row data
 if(excelReader.FieldCount <= 0)
 {
 curRowIndex++;
 continue;
 }
 // Read the complete data of each row
 string[] datas = new string[excelReader.FieldCount];
 for(int j = 0; j < excelReader.FieldCount; ++j)
 {
 // You can directly read the specified type of data , However, only limited data types are supported , Read uniformly here string, Then data conversion
 //excelReader.GetInt32(j); excelReader.GetFloat(j);

 // Read every cell data
 datas[j] = excelReader.GetString(j);
 }

 switch(curRowIndex)
 {
 case specialSignRow:
 // Special mark line
 string specialSignStr = datas[0];
 if(specialSignStr.Length >= 4)
 {
 excelMediumData.isValid = specialSignStr[0] == 'T';
 excelMediumData.isCreateCSharp = specialSignStr[1] == 'T';
 excelMediumData.isCreateAssignment = specialSignStr[2] == 'T';
 excelMediumData.isCreateAsset = specialSignStr[3] == 'T';
 }
 else
 {
 Debug.LogError(&quot; Not resolved to special tag &quot;);
 }
 break;
 case excelNodeRow:
 // Data comment line
 excelMediumData.propertyNodeArray = datas;
 break;
 case excelNameRow:
 // Data name row
 excelMediumData.propertyNameArray = datas;
 // Comment column number
 for(int i = 0; i < datas.Length; i++)
 {
 if(string.IsNullOrEmpty(datas[i]) || datas[i].StartsWith(annotationSign))
 excelMediumData.annotationColList.Add(i);
 }
 break;
 case excelTypeRow:
 // Data type row
 excelMediumData.propertyTypeArray = datas;
 break;
 default:
 // Data content line
 excelMediumData.allRowItemList.Add(datas);
 // Comment line number
 if(string.IsNullOrEmpty(datas[0]) || datas[0].StartsWith(annotationSign))
 excelMediumData.annotationRowList.Add(excelMediumData.allRowItemList.Count - 1);
 break;
 }
 //
 curRowIndex++;
 }

 if(CheckExcelMediumData(ref excelMediumData))
 {
 Debug.Log(&quot; Read Excel success &quot;);
 return excelMediumData;
 }
 else
 {
 Debug.LogError(&quot; Read Excel Failure &quot;);
 return null;
 }
 }

 // check Excel data
 private static bool CheckExcelMediumData(ref ExcelMediumData mediumData)
 {
 if(mediumData == null)
 return false;

 // Check data validity

 if(!mediumData.isValid)
 {
 Debug.LogError(&quot;Excel Marked invalid &quot;);
 return false;
 }

 if(string.IsNullOrEmpty(mediumData.excelName))
 {
 Debug.LogError(&quot;Excel The name is empty. &quot;);
 return false;
 }

 if(mediumData.propertyNameArray == null || mediumData.propertyNameArray.Length == 0)
 {
 Debug.LogError(&quot; Data name not resolved &quot;);
 return false;
 }
 if(mediumData.propertyTypeArray == null || mediumData.propertyTypeArray.Length == 0)
 {
 Debug.LogError(&quot; Not resolved to data type &quot;);
 return false;
 }
 if(mediumData.propertyNameArray.Length != mediumData.propertyTypeArray.Length)
 {
 Debug.LogError(&quot; The data name is inconsistent with the number of data types &quot;);
 return false;
 }
 if(mediumData.allRowItemList.Count == 0)
 {
 Debug.LogError(&quot; The data content is empty &quot;);
 return false;
 }

 if(mediumData.propertyNameArray[0] != &quot;id&quot;)
 {
 Debug.LogError(&quot; The first field must be id Field &quot;);
 return false;
 }

 return true;
 }

 #endregion

}

C# Code generation class :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Linq;
using System;

public class ExcelCodeCreater
{

 // Create code , Generate the data C# class
 public static string CreateCodeStrByExcelData(ExcelMediumData excelMediumData)
 {
 if(excelMediumData == null)
 return null;

 // Row data class name
 string itemClassName = excelMediumData.excelName + &quot;ExcelItem&quot;;
 // Overall data class name
 string dataClassName = excelMediumData.excelName + &quot;ExcelData&quot;;

 // Start generating classes
 StringBuilder classSource = new StringBuilder();
 classSource.AppendLine(&quot;/*Auto Create, Don't Edit !!!*/&quot;);
 classSource.AppendLine();
 // Add reference
 classSource.AppendLine(&quot;using UnityEngine;&quot;);
 classSource.AppendLine(&quot;using System.Collections.Generic;&quot;);
 classSource.AppendLine(&quot;using System;&quot;);
 classSource.AppendLine(&quot;using System.IO;&quot;);
 classSource.AppendLine();
 // Generate CSharp Data class
 if(excelMediumData.isCreateCSharp)
 {
 // Generate row data class , Record each line of data
 classSource.AppendLine(CreateExcelRowItemClass(itemClassName,excelMediumData));
 classSource.AppendLine();
 // Generate overall data class , Record the whole Excel All rows of data
 classSource.AppendLine(CreateExcelAllDataClass(dataClassName,itemClassName,excelMediumData));
 classSource.AppendLine();
 }
 // Generate Asset Create a class
 if(excelMediumData.isCreateAssignment)
 {
 // Generate Asset Operation class , For automatic creation of Excel Corresponding Asset File and assign
 classSource.AppendLine(CreateExcelAssetClass(excelMediumData));
 classSource.AppendLine();
 }
 //
 return classSource.ToString();
 }

 //----------

 // Generate row data class
 private static string CreateExcelRowItemClass(string itemClassName,ExcelMediumData excelMediumData)
 {
 // Generate Excel Row data class
 StringBuilder classSource = new StringBuilder();
 // Class name
 classSource.AppendLine(&quot;[Serializable]&quot;);
 classSource.AppendLine($&quot;public class {itemClassName} : ExcelItemBase&quot;);
 classSource.AppendLine(&quot;{&quot;);
 // Declare all fields
 for(int i = 0; i < excelMediumData.propertyNameArray.Length; i++)
 {
 // Skip comment field
 if(excelMediumData.annotationColList.Contains(i))
 continue;

 // Add notes
 if(i < excelMediumData.propertyNodeArray.Length)
 {
 string propertyNode = excelMediumData.propertyNodeArray[i];
 if(!string.IsNullOrEmpty(propertyNode))
 {
 classSource.AppendLine(&quot;\t/// <summary>&quot;);
 classSource.AppendLine($&quot;\t/// {propertyNode}&quot;);
 classSource.AppendLine(&quot;\t/// </summary>>&quot;);
 }
 }

 // Declare the fields of the row data class
 string propertyName = excelMediumData.propertyNameArray[i];
 string propertyType = excelMediumData.propertyTypeArray[i];
 string typeStr = GetPropertyType(propertyType);
 classSource.AppendLine($&quot;\tpublic {typeStr} {propertyName};&quot;);
 }
 classSource.AppendLine(&quot;}&quot;);
 return classSource.ToString();
 }

 //----------

 // Generate overall data class
 private static string CreateExcelAllDataClass(string dataClassName,string itemClassName,ExcelMediumData excelMediumData)
 {
 StringBuilder classSource = new StringBuilder();
 // Class name
 classSource.AppendLine($&quot;public class {dataClassName} : ExcelDataBase<{itemClassName}>&quot;);
 classSource.AppendLine(&quot;{&quot;);
 // Declaration field , Row data class array
 classSource.AppendLine($&quot;\tpublic {itemClassName}[] items;&quot;);
 classSource.AppendLine();
 //id Field type
 string idTypeStr = GetPropertyType(excelMediumData.propertyTypeArray[0]);
 // Declaration Dictionary
 classSource.AppendLine($&quot;\tpublic Dictionary<{idTypeStr},{itemClassName}> itemDic = new Dictionary<{idTypeStr},{itemClassName}>();&quot;);
 classSource.AppendLine();
 // Field initialization method
 classSource.AppendLine(&quot;\tpublic void Init()&quot;);
 classSource.AppendLine(&quot;\t{&quot;);
 classSource.AppendLine(&quot;\t\titemDic.Clear();&quot;);
 classSource.AppendLine(&quot;\t\tif(items != null && items.Length > 0)&quot;);
 classSource.AppendLine(&quot;\t\t{&quot;);
 classSource.AppendLine(&quot;\t\t\tfor(int i = 0; i < items.Length; i++)&quot;);
 classSource.AppendLine(&quot;\t\t\t{&quot;);
 classSource.AppendLine(&quot;\t\t\t\titemDic.Add(items[i].id, items[i]);&quot;);
 classSource.AppendLine(&quot;\t\t\t}&quot;);
 classSource.AppendLine(&quot;\t\t}&quot;);
 classSource.AppendLine(&quot;\t}&quot;);
 classSource.AppendLine();
 // Dictionary acquisition method
 classSource.AppendLine($&quot;\tpublic {itemClassName} Get{itemClassName}({idTypeStr} id)&quot;);
 classSource.AppendLine(&quot;\t{&quot;);
 classSource.AppendLine(&quot;\t\tif(itemDic.ContainsKey(id))&quot;);
 classSource.AppendLine(&quot;\t\t\treturn itemDic[id];&quot;);
 classSource.AppendLine(&quot;\t\telse&quot;);
 classSource.AppendLine(&quot;\t\t\treturn null;&quot;);
 classSource.AppendLine(&quot;\t}&quot;);

 // Each field Get function
 classSource.AppendLine(&quot;\t#region --- Get Method ---&quot;);
 classSource.AppendLine();

 for(int i = 1; i < excelMediumData.propertyNameArray.Length; i++)
 {
 if(excelMediumData.annotationColList.Contains(i))
 continue;
 string propertyName = excelMediumData.propertyNameArray[i];
 string propertyType = excelMediumData.propertyTypeArray[i];
 // Each field Get function
 classSource.AppendLine(CreateCodePropertyMethod(itemClassName,idTypeStr,propertyName,propertyType));
 }
 classSource.AppendLine(&quot;\t#endregion&quot;);
 classSource.AppendLine(&quot;}&quot;);
 return classSource.ToString();
 }

 // The generated data field corresponds to Get Method
 private static string CreateCodePropertyMethod(string itemClassName,string idTypeStr,string propertyName,string propertyType)
 {
 StringBuilder methodBuilder = new StringBuilder();
 string itemNameStr = propertyName.FirstOrDefault().ToString().ToUpper() + propertyName.Substring(1);
 string itemTypeStr = GetPropertyType(propertyType);
 // Field Get function
 methodBuilder.AppendLine($&quot;\tpublic {itemTypeStr} Get{itemNameStr}({idTypeStr} id)&quot;);
 methodBuilder.AppendLine(&quot;\t{&quot;);
 methodBuilder.AppendLine($&quot;\t\tvar item = Get{itemClassName}(id);&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item == null)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine($&quot;\t\treturn item.{propertyName};&quot;);
 methodBuilder.AppendLine(&quot;\t}&quot;);
 // If it's a one-dimensional array
 if(propertyType.Contains(&quot;[]&quot;))
 {
 //typeStr:int[] or IntArr[] , Return value :int or IntArr
 //string itemTypeStr1d = GetPropertyType(propertyType.Replace(&quot;[]&quot;,&quot;&quot;));
 string itemTypeStr1d = itemTypeStr.Replace(&quot;[]&quot;,&quot;&quot;);
 methodBuilder.AppendLine($&quot;\tpublic {itemTypeStr1d} Get{itemNameStr}({idTypeStr} id, int index)&quot;);
 methodBuilder.AppendLine(&quot;\t{&quot;);
 methodBuilder.AppendLine($&quot;\t\tvar item0 = Get{itemClassName} (id);&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item0 == null)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine($&quot;\t\tvar item1 = item0.{propertyName};&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item1 == null || index < 0 || index >= item1.Length)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine(&quot;\t\treturn item1[index];&quot;);
 methodBuilder.AppendLine(&quot;\t}&quot;);
 }
 // If it's a two-dimensional array
 if(propertyType.Contains(&quot;[][]&quot;))
 {
 //propertyType:int[][],  Return value :int
 string itemTypeStr1d = GetPropertyType(propertyType.Replace(&quot;[][]&quot;,&quot;&quot;));
 methodBuilder.AppendLine($&quot;\tpublic {itemTypeStr1d} Get{itemNameStr}({idTypeStr} id, int index1, int index2)&quot;);
 methodBuilder.AppendLine(&quot;\t{&quot;);
 methodBuilder.AppendLine($&quot;\t\tvar item0 = Get{itemClassName}(id);&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item0 == null)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine($&quot;\t\tvar item1 = item0.{propertyName};&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item1 == null || index1 < 0 || index1 >= item1.Length)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine(&quot;\t\tvar item2 = item1[index1];&quot;);
 methodBuilder.AppendLine(&quot;\t\tif(item2.array == null || index2 < 0 || index2 >= item2.array.Length)&quot;);
 methodBuilder.AppendLine(&quot;\t\t\treturn default;&quot;);
 methodBuilder.AppendLine(&quot;\t\treturn item2.array[index2];&quot;);
 methodBuilder.AppendLine(&quot;\t}&quot;);
 }
 //
 return methodBuilder.ToString();
 }

 //----------

 // Generate Asset Create a class
 private static string CreateExcelAssetClass(ExcelMediumData excelMediumData)
 {
 string itemClassName = excelMediumData.excelName + &quot;ExcelItem&quot;;
 string dataClassName = excelMediumData.excelName + &quot;ExcelData&quot;;
 string assignmentClassName = excelMediumData.excelName + &quot;AssetAssignment&quot;;

 StringBuilder classSource = new StringBuilder();
 classSource.AppendLine(&quot;#if UNITY_EDITOR&quot;);
 // Class name
 classSource.AppendLine($&quot;public class {assignmentClassName}&quot;);
 classSource.AppendLine(&quot;{&quot;);
 // Method name
 classSource.AppendLine(&quot;\tpublic static bool CreateAsset(ExcelMediumData excelMediumData, string excelAssetPath)&quot;);
 // Method body , If necessary, you can join try/catch
 classSource.AppendLine(&quot;\t{&quot;);
 classSource.AppendLine(&quot;\t\tvar allRowItemDicList = excelMediumData.GetAllRowItemDicList();&quot;);
 classSource.AppendLine(&quot;\t\tif(allRowItemDicList == null || allRowItemDicList.Count == 0)&quot;);
 classSource.AppendLine(&quot;\t\t\treturn false;&quot;);
 classSource.AppendLine();
 classSource.AppendLine(&quot;\t\tint rowCount = allRowItemDicList.Count;&quot;);
 classSource.AppendLine($&quot;\t\t{dataClassName} excelDataAsset = ScriptableObject.CreateInstance<{dataClassName}>();&quot;);
 classSource.AppendLine($&quot;\t\texcelDataAsset.items = new {itemClassName}[rowCount];&quot;);
 classSource.AppendLine();
 classSource.AppendLine(&quot;\t\tfor(int i = 0; i < rowCount; i++)&quot;);
 classSource.AppendLine(&quot;\t\t{&quot;);
 classSource.AppendLine(&quot;\t\t\tvar itemRowDic = allRowItemDicList[i];&quot;);
 classSource.AppendLine($&quot;\t\t\texcelDataAsset.items[i] = new {itemClassName}();&quot;);

 for(int i = 0; i < excelMediumData.propertyNameArray.Length; i++)
 {
 if(excelMediumData.annotationColList.Contains(i))
 continue;
 string propertyName = excelMediumData.propertyNameArray[i];
 string propertyType = excelMediumData.propertyTypeArray[i];
 classSource.Append($&quot;\t\t\texcelDataAsset.items[i].{propertyName} = &quot;);
 classSource.Append(AssignmentCodeProperty(propertyName,propertyType));
 classSource.AppendLine(&quot;;&quot;);
 }
 classSource.AppendLine(&quot;\t\t}&quot;);
 classSource.AppendLine(&quot;\t\tif(!Directory.Exists(excelAssetPath))&quot;);
 classSource.AppendLine(&quot;\t\t\tDirectory.CreateDirectory(excelAssetPath);&quot;);
 classSource.AppendLine($&quot;\t\tstring fullPath = Path.Combine(excelAssetPath,typeof({dataClassName}).Name) + \&quot;.asset\&quot;;&quot;);
 classSource.AppendLine(&quot;\t\tUnityEditor.AssetDatabase.DeleteAsset(fullPath);&quot;);
 classSource.AppendLine(&quot;\t\tUnityEditor.AssetDatabase.CreateAsset(excelDataAsset,fullPath);&quot;);
 classSource.AppendLine(&quot;\t\tUnityEditor.AssetDatabase.Refresh();&quot;);
 classSource.AppendLine(&quot;\t\treturn true;&quot;);
 classSource.AppendLine(&quot;\t}&quot;);
 // 
 classSource.AppendLine(&quot;}&quot;);
 classSource.AppendLine(&quot;#endif&quot;);
 return classSource.ToString();
 }

 // Statement Asset Operation field
 private static string AssignmentCodeProperty(string propertyName,string propertyType)
 {
 string stringValue = $&quot;itemRowDic[\&quot;{propertyName}\&quot;]&quot;;
 string typeStr = GetPropertyType(propertyType);
 switch(typeStr)
 {
 // Field
 case &quot;int&quot;:
 return &quot;StringUtility.StringToInt(&quot; + stringValue + &quot;)&quot;;
 case &quot;float&quot;:
 return &quot;StringUtility.StringToFloat(&quot; + stringValue + &quot;)&quot;;
 case &quot;bool&quot;:
 return &quot;StringUtility.StringToBool(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2&quot;:
 return &quot;StringUtility.StringToVector2(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3&quot;:
 return &quot;StringUtility.StringToVector3(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2Int&quot;:
 return &quot;StringUtility.StringToVector2Int(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3Int&quot;:
 return &quot;StringUtility.StringToVector3Int(&quot; + stringValue + &quot;)&quot;;
 case &quot;Color&quot;:
 return &quot;StringUtility.StringToColor(&quot; + stringValue + &quot;)&quot;;
 case &quot;Color32&quot;:
 return &quot;StringUtility.StringToColor32(&quot; + stringValue + &quot;)&quot;;
 case &quot;string&quot;:
 return stringValue;
 // A one-dimensional
 case &quot;int[]&quot;:
 return &quot;StringUtility.StringToIntArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;float[]&quot;:
 return &quot;StringUtility.StringToFloatArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;bool[]&quot;:
 return &quot;StringUtility.StringToBoolArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2[]&quot;:
 return &quot;StringUtility.StringToVector2Array(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3[]&quot;:
 return &quot;StringUtility.StringToVector3Array(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2Int[]&quot;:
 return &quot;StringUtility.StringToVector2IntArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3Int[]&quot;:
 return &quot;StringUtility.StringToVector3IntArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;Color[]&quot;:
 return &quot;StringUtility.StringToColorArray(&quot; + stringValue + &quot;)&quot;;
 case &quot;Color32[]&quot;:
 return &quot;StringUtility.StringToColor32Array(&quot; + stringValue + &quot;)&quot;;
 case &quot;string[]&quot;:
 return &quot;StringUtility.StringToStringArray(&quot; + stringValue + &quot;)&quot;;
 // A two-dimensional
 case &quot;IntArr[]&quot;:
 return &quot;StringUtility.StringToIntArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;FloatArr[]&quot;:
 return &quot;StringUtility.StringToFloatArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;BoolArr[]&quot;:
 return &quot;StringUtility.StringToBoolArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2Arr[]&quot;:
 return &quot;StringUtility.StringToVector2Array2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3Arr[]&quot;:
 return &quot;StringUtility.StringToVector3Array2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector2IntArr[]&quot;:
 return &quot;StringUtility.StringToVector2IntArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;Vector3IntArr[]&quot;:
 return &quot;StringUtility.StringToVector3IntArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;ColorArr[]&quot;:
 return &quot;StringUtility.StringToColorArray2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;Color32Arr[]&quot;:
 return &quot;StringUtility.StringToColor32Array2D(&quot; + stringValue + &quot;)&quot;;
 case &quot;StringArr[]&quot;:
 return &quot;StringUtility.StringToStringArray2D(&quot; + stringValue + &quot;)&quot;;
 default:
 // enumeration
 if(propertyType.StartsWith(&quot;enum&quot;))
 {
 string enumType = propertyType.Split('|').FirstOrDefault();
 string enumName = propertyType.Split('|').LastOrDefault();
 if(enumType == &quot;enum&quot;)
 return &quot;StringUtility.StringToEnum<&quot; + enumName + &quot;>(&quot; + stringValue + &quot;)&quot;;
 else if(enumType == &quot;enum[]&quot;)
 return &quot;StringUtility.StringToEnumArray<&quot; + enumName + &quot;>(&quot; + stringValue + &quot;)&quot;;
 else if(enumType == &quot;enum[][]&quot;)
 return &quot;StringUtility.StringToEnumArray2D<&quot; + enumName + &quot;>(&quot; + stringValue + &quot;)&quot;;
 }
 return stringValue;
 }
 }

 // Determine the field type
 private static string GetPropertyType(string propertyType)
 {
 string lowerType = propertyType.ToLower();
 switch(lowerType)
 {
 case &quot;int&quot;:
 return &quot;int&quot;;
 case &quot;int[]&quot;:
 return &quot;int[]&quot;;
 case &quot;int[][]&quot;:
 return &quot;IntArr[]&quot;;
 case &quot;float&quot;:
 return &quot;float&quot;;
 case &quot;float[]&quot;:
 return &quot;float[]&quot;;
 case &quot;float[][]&quot;:
 return &quot;FloatArr[]&quot;;
 case &quot;bool&quot;:
 return &quot;bool&quot;;
 case &quot;bool[]&quot;:
 return &quot;bool[]&quot;;
 case &quot;bool[][]&quot;:
 return &quot;BoolArr[]&quot;;
 case &quot;string&quot;:
 return &quot;string&quot;;
 case &quot;string[]&quot;:
 return &quot;string[]&quot;;
 case &quot;string[][]&quot;:
 return &quot;StringArr[]&quot;;

 case &quot;vector2&quot;:
 return &quot;Vector2&quot;;
 case &quot;vector2[]&quot;:
 return &quot;Vector2[]&quot;;
 case &quot;vector2[][]&quot;:
 return &quot;Vector2Arr[]&quot;;
 case &quot;vector2int&quot;:
 return &quot;Vector2Int&quot;;
 case &quot;vector2int[]&quot;:
 return &quot;Vector2Int[]&quot;;
 case &quot;vector2int[][]&quot;:
 return &quot;Vector2IntArr[]&quot;;

 case &quot;vector3&quot;:
 return &quot;Vector3&quot;;
 case &quot;vector3[]&quot;:
 return &quot;Vector3[]&quot;;
 case &quot;vector3[][]&quot;:
 return &quot;Vector3Arr[]&quot;;
 case &quot;vector3int&quot;:
 return &quot;Vector3Int&quot;;
 case &quot;vector3int[]&quot;:
 return &quot;Vector3Int[]&quot;;
 case &quot;vector3int[][]&quot;:
 return &quot;Vector3IntArr[]&quot;;

 case &quot;color&quot;:
 return &quot;Color&quot;;
 case &quot;color[]&quot;:
 return &quot;Color[]&quot;;
 case &quot;color[][]&quot;:
 return &quot;ColorArr[]&quot;;
 case &quot;color32&quot;:
 return &quot;Color32&quot;;
 case &quot;color32[]&quot;:
 return &quot;Color32[]&quot;;
 case &quot;color32[][]&quot;:
 return &quot;Color32Arr[]&quot;;

 default:
 if(propertyType.StartsWith(&quot;enum&quot;))
 {
 string enumType = propertyType.Split('|').FirstOrDefault();
 string enumName = propertyType.Split('|').LastOrDefault();
 switch(enumType)
 {
 case &quot;enum&quot;:
 return enumName;
 case &quot;enum[]&quot;:
 return $&quot;{enumName}[]&quot;;
 case &quot;enum[][]&quot;:
 return $&quot;EnumArr<{enumName}>[]&quot;;
 default:
 break;
 }
 }
 return &quot;string&quot;;
 }
 }

}

Excel Data intermediate class :

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

//Excel Intermediate data
public class ExcelMediumData
{
 //Excel name
 public string excelName;

 //Excel Whether it works
 public bool isValid = false;
 // Whether to generate CSharp Data class
 public bool isCreateCSharp = false;
 // Whether to generate Asset Create a class
 public bool isCreateAssignment = false;
 // Whether to generate Asset file
 public bool isCreateAsset = false;

 // Data annotation
 public string[] propertyNodeArray = null;
 // Data name
 public string[] propertyNameArray = null;
 // data type
 public string[] propertyTypeArray = null;
 //List< Data content of each line >
 public List<string[]> allRowItemList = new List<string[]>();

 // Comment line number
 public List<int> annotationRowList = new List<int>();
 // Comment column number
 public List<int> annotationColList = new List<int>();

 //List< Each line of data >,List<Dictionary< Cell field name ,  Cell field value >>
 public List<Dictionary<string,string>> GetAllRowItemDicList()
 {
 if(propertyNameArray == null || propertyNameArray.Length == 0)
 return null;
 if(allRowItemList.Count == 0)
 return null;

 List<Dictionary<string,string>> allRowItemDicList = new List<Dictionary<string,string>>(allRowItemList.Count);

 for(int i = 0; i < allRowItemList.Count; i++)
 {
 string[] rowArray = allRowItemList[i];
 // Skip empty data
 if(rowArray == null || rowArray.Length == 0)
 continue;
 // Skip annotation data
 if(annotationRowList.Contains(i))
 continue;

 // Each line of data , Corresponding field name and field value
 Dictionary<string,string> rowDic = new Dictionary<string,string>();
 for(int j = 0; j < propertyNameArray.Length; j++)
 {
 // Skip comment field
 if(annotationColList.Contains(j))
 continue;

 string propertyName = propertyNameArray[j];
 string propertyValue = j < rowArray.Length ? rowArray[j] : null;
 rowDic[propertyName] = propertyValue;
 }
 allRowItemDicList.Add(rowDic);
 }
 return allRowItemDicList;
 }

}

Excel Data base class 、 The extension class :

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

public class ExcelDataBase<T> : ScriptableObject where T : ExcelItemBase
{

}

public class ExcelItemBase
{

}


[Serializable]
public struct StringArr
{
 public string[] array;
}
[Serializable]
public struct IntArr
{
 public int[] array;
}
[Serializable]
public struct FloatArr
{
 public float[] array;
}
[Serializable]
public struct BoolArr
{
 public bool[] array;
}

[Serializable]
public struct Vector2Arr
{
 public Vector2[] array;
}
[Serializable]
public struct Vector3Arr
{
 public Vector3[] array;
}
[Serializable]
public struct Vector2IntArr
{
 public Vector2Int[] array;
}
[Serializable]
public struct Vector3IntArr
{
 public Vector3Int[] array;
}
[Serializable]
public struct ColorArr
{
 public Color[] array;
}
[Serializable]
public struct Color32Arr
{
 public Color32[] array;
}

//// Generic enumeration serialization is not supported
//[Serializable]
//public struct EnumArr<T> where T : Enum
//{
// public T[] array;
//}

String utility class :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
using System;
using System.Text;
using System.Linq;
using System.Runtime.CompilerServices;

public static class StringUtility
{

 #region --- AddColor ---

 public static string AddColor(object obj,Color color)
 {
 return AddColor(obj,color);
 }
 public static string AddColor(this string str,Color color)
 {
 // Convert the color to 16 Base string , Add to rich text
 return string.Format(&quot;<color=#{0}>{1}</color>&quot;,ColorUtility.ToHtmlStringRGBA(color),str);
 }
 public static string AddColor(string str1,string str2,Color color)
 {
 return AddColor(str1 + str2,color);
 }
 public static string AddColor(string str1,string str2,string str3,Color color)
 {
 return AddColor(str1 + str2 + str3,color);
 }

 #endregion

 #region --- string length ---

 /// <summary>
 ///  Reduce string length
 /// </summary>
 /// <param name=&quot;targetStr&quot;></param>
 /// <param name=&quot;targetLength&quot;> Target length , English characters ==1, Chinese characters ==2</param>
 /// <returns></returns>
 public static string AbbrevStringWithinLength(string targetStr,int targetLength,string abbrevPostfix)
 {
 //C# Actual statistics : The length of a Chinese character ==1, English character length ==1
 //UI Display requirements : The length of a Chinese character ==2, English character length ==1

 // Calibration parameters
 if(string.IsNullOrEmpty(targetStr) || targetLength <= 0)
 return targetStr;
 // String length  * 2 <=  Target length , Even if it is all Chinese, it is within the length range
 if(targetStr.Length * 2 <= targetLength)
 return targetStr;
 // Traversal character
 char[] chars = targetStr.ToCharArray();
 int curLen = 0;
 for(int i = 0; i < chars.Length; i++)
 {
 // Accumulate string length
 if(chars[i] >= 0x4e00 && chars[i] <= 0x9fbb)
 curLen += 2;
 else
 curLen += 1;

 // If the cumulative length of the current position exceeds the target length , take 0~i-1, namely Substring(0,i)
 if(curLen > targetLength)
 return targetStr.Substring(0,i) + abbrevPostfix;
 }
 return targetStr;
 }

 #endregion

 #region --- String To Array ---

 //string

 public static byte StringToByte(string valueStr)
 {
 byte value;
 if(byte.TryParse(valueStr,out value))
 return value;
 else
 return 0;
 }

 public static string[] StringToStringArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 return valueStr.Split(splitSign);
 }

 public static StringArr[] StringToStringArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 StringArr[] arrArr = new StringArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new StringArr()
 {
 array = strArr1[i].Split(splitSign2)
 };

 }
 return arrArr;
 }

 //int

 public static int StringToInt(string valueStr)
 {
 int value;
 if(int.TryParse(valueStr,out value))
 return value;
 else
 return 0;
 }

 public static int[] StringToIntArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] valueArr = valueStr.Split(splitSign);
 if(valueArr == null || valueArr.Length == 0)
 return null;

 int[] intArr = new int[valueArr.Length];
 for(int i = 0; i < valueArr.Length; i++)
 {
 intArr[i] = StringToInt(valueArr[i]);
 }
 return intArr;
 }

 public static IntArr[] StringToIntArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 IntArr[] arrArr = new IntArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new IntArr()
 {
 array = StringToIntArray(strArr1[i],splitSign2)
 };

 }
 return arrArr;
 }

 //float

 public static float StringToFloat(string valueStr)
 {
 float value;
 if(float.TryParse(valueStr,out value))
 return value;
 else
 return 0;
 }

 public static float[] StringToFloatArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] valueArr = valueStr.Split(splitSign);
 if(valueArr == null || valueArr.Length == 0)
 return null;

 float[] floatArr = new float[valueArr.Length];
 for(int i = 0; i < valueArr.Length; i++)
 {
 floatArr[i] = StringToFloat(valueArr[i]);
 }
 return floatArr;
 }

 public static FloatArr[] StringToFloatArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 FloatArr[] arrArr = new FloatArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new FloatArr()
 {
 array = StringToFloatArray(strArr1[i],splitSign2)
 };

 }
 return arrArr;
 }

 //bool

 public static bool StringToBool(string valueStr)
 {
 bool value;
 if(bool.TryParse(valueStr,out value))
 return value;
 else
 return false;
 }

 public static bool[] StringToBoolArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] valueArr = valueStr.Split(splitSign);
 if(valueArr == null || valueArr.Length == 0)
 return null;

 bool[] boolArr = new bool[valueArr.Length];
 for(int i = 0; i < valueArr.Length; i++)
 {
 boolArr[i] = StringToBool(valueArr[i]);
 }
 return boolArr;
 }

 public static BoolArr[] StringToBoolArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 BoolArr[] arrArr = new BoolArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new BoolArr()
 {
 array = StringToBoolArray(strArr1[i],splitSign2)
 };

 }
 return arrArr;
 }

 //enum

 public static T StringToEnum<T>(string valueStr) where T : Enum
 {
 if(string.IsNullOrEmpty(valueStr))
 return (T)default;

 // First verify whether the string is an enumeration value
 int intValue;
 if(int.TryParse(valueStr,out intValue))
 {
 if(Enum.IsDefined(typeof(T),intValue))
 return (T)Enum.ToObject(typeof(T),intValue);
 }
 // If it is not an enumerated value , Treat as enum name
 try
 {
 T t = (T)Enum.Parse(typeof(T),valueStr);
 if(Enum.IsDefined(typeof(T),t))
 return t;
 }
 catch(Exception e)
 {
 Debug.LogError(e);
 }
 Debug.LogError(string.Format(&quot; Parsing enumeration error  {0} : {1}&quot;,typeof(T),valueStr));
 return (T)default;
 }

 public static T[] StringToEnumArray<T>(string valueStr,char splitSign = '|') where T : Enum
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] valueArr = valueStr.Split(splitSign);
 if(valueArr == null || valueArr.Length == 0)
 return null;

 T[] enumArr = new T[valueArr.Length];
 for(int i = 0; i < valueArr.Length; i++)
 {
 enumArr[i] = StringToEnum<T>(valueArr[i]);
 }
 return enumArr;
 }

 //// Generic enumeration serialization is not supported
 //public static EnumArr<T>[] StringToEnumArray2D<T>(string valueStr,char splitSign1 = '&',char splitSign2 = '|') where T : Enum
 //{
 // if(string.IsNullOrEmpty(valueStr))
 // return null;
 // string[] strArr1 = valueStr.Split(splitSign1);
 // if(strArr1.Length == 0)
 // return null;

 // EnumArr<T>[] arrArr = new EnumArr<T>[strArr1.Length];
 // for(int i = 0; i < strArr1.Length; i++)
 // {
 // arrArr[i] = new EnumArr<T>()
 // {
 // array = StringToEnumArray<T>(strArr1[i],splitSign2)
 // };

 // }
 // return arrArr;
 //}

 //vector2

 public static Vector2 StringToVector2(string valueStr,char splitSign = ',')
 {
 Vector2 value = Vector2.zero;
 if(!string.IsNullOrEmpty(valueStr))
 {
 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray != null && stringArray.Length >= 2)
 {
 value.x = StringToFloat(stringArray[0]);
 value.y = StringToFloat(stringArray[1]);
 return value;
 }
 }
 Debug.LogWarning(&quot;String to Vector2 error&quot;);
 return value;
 }

 public static Vector2[] StringToVector2Array(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Vector2[] vector2s = new Vector2[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 vector2s[i] = StringToVector2(stringArray[i]);
 }
 return vector2s;
 }

 public static Vector2Arr[] StringToVector2Array2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 Vector2Arr[] arrArr = new Vector2Arr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new Vector2Arr()
 {
 array = StringToVector2Array(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }

 //vector3

 public static Vector3 StringToVector3(string valueStr,char splitSign = ',')
 {
 Vector3 value = Vector3.zero;
 if(!string.IsNullOrEmpty(valueStr))
 {
 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray.Length >= 3)
 {
 value.x = StringToFloat(stringArray[0]);
 value.y = StringToFloat(stringArray[1]);
 value.z = StringToFloat(stringArray[2]);
 return value;
 }
 }
 Debug.LogWarning(&quot;String to Vector3 error&quot;);
 return value;
 }

 public static Vector3[] StringToVector3Array(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Vector3[] vector3s = new Vector3[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 vector3s[i] = StringToVector3(stringArray[i]);
 }
 return vector3s;
 }

 public static Vector3Arr[] StringToVector3Array2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 Vector3Arr[] arrArr = new Vector3Arr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new Vector3Arr()
 {
 array = StringToVector3Array(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }

 //vector2Int

 public static Vector2Int StringToVector2Int(string valueStr,char splitSign = ',')
 {
 Vector2Int value = Vector2Int.zero;
 if(!string.IsNullOrEmpty(valueStr))
 {
 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray != null && stringArray.Length >= 2)
 {
 value.x = StringToInt(stringArray[0]);
 value.y = StringToInt(stringArray[1]);
 return value;
 }
 }
 Debug.LogWarning(&quot;String to Vector2Int error&quot;);
 return value;
 }

 public static Vector2Int[] StringToVector2IntArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Vector2Int[] vector2Ints = new Vector2Int[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 vector2Ints[i] = StringToVector2Int(stringArray[i]);
 }
 return vector2Ints;
 }

 public static Vector2IntArr[] StringToVector2IntArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 Vector2IntArr[] arrArr = new Vector2IntArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new Vector2IntArr()
 {
 array = StringToVector2IntArray(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }

 //vector3Int

 public static Vector3Int StringToVector3Int(string valueStr,char splitSign = ',')
 {
 Vector3Int value = Vector3Int.zero;
 if(!string.IsNullOrEmpty(valueStr))
 {
 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray.Length >= 3)
 {
 value.x = StringToInt(stringArray[0]);
 value.y = StringToInt(stringArray[1]);
 value.z = StringToInt(stringArray[2]);
 return value;
 }
 }
 Debug.LogWarning(&quot;String to Vector3 error&quot;);
 return value;
 }

 public static Vector3Int[] StringToVector3IntArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Vector3Int[] vector3Ints = new Vector3Int[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 vector3Ints[i] = StringToVector3Int(stringArray[i]);
 }
 return vector3Ints;
 }

 public static Vector3IntArr[] StringToVector3IntArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 Vector3IntArr[] arrArr = new Vector3IntArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new Vector3IntArr()
 {
 array = StringToVector3IntArray(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }

 //color

 public static Color StringToColor(string valueStr,char splitSign = ',')
 {
 if(string.IsNullOrEmpty(valueStr))
 return Color.white;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray.Length < 3)
 return Color.white;

 Color color = new Color()
 {
 r = StringToFloat(stringArray[0]),
 g = StringToFloat(stringArray[1]),
 b = StringToFloat(stringArray[2]),
 a = stringArray.Length < 4 ? 1 : StringToFloat(stringArray[3])
 };
 return color;
 }
 public static Color32 StringToColor32(string valueStr,char splitSign = ',')
 {
 if(string.IsNullOrEmpty(valueStr))
 return Color.white;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray.Length < 3)
 return Color.white;

 Color32 color = new Color32()
 {
 r = StringToByte(stringArray[0]),
 g = StringToByte(stringArray[1]),
 b = StringToByte(stringArray[2]),
 a = stringArray.Length < 4 ? (byte)1 : StringToByte(stringArray[3])
 };
 return color;
 }

 public static Color[] StringToColorArray(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Color[] colors = new Color[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 colors[i] = StringToColor(stringArray[i]);
 }
 return colors;
 }

 public static Color32[] StringToColor32Array(string valueStr,char splitSign = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;

 string[] stringArray = valueStr.Split(splitSign);
 if(stringArray == null || stringArray.Length == 0)
 return null;

 Color32[] colors = new Color32[stringArray.Length];
 for(int i = 0; i < stringArray.Length; i++)
 {
 colors[i] = StringToColor32(stringArray[i]);
 }
 return colors;
 }

 public static ColorArr[] StringToColorArray2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 ColorArr[] arrArr = new ColorArr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new ColorArr()
 {
 array = StringToColorArray(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }
 public static Color32Arr[] StringToColor32Array2D(string valueStr,char splitSign1 = '&',char splitSign2 = '|')
 {
 if(string.IsNullOrEmpty(valueStr))
 return null;
 string[] strArr1 = valueStr.Split(splitSign1);
 if(strArr1.Length == 0)
 return null;

 Color32Arr[] arrArr = new Color32Arr[strArr1.Length];
 for(int i = 0; i < strArr1.Length; i++)
 {
 arrArr[i] = new Color32Arr()
 {
 array = StringToColor32Array(strArr1[i],splitSign2)
 };
 }
 return arrArr;
 }

 #endregion

 #region MyRegion

 public static string GetRandomString(int length)
 {
 StringBuilder builder = new StringBuilder();
 string abc = &quot;abcdefghijklmnopqrstuvwxyzo0123456789QWERTYUIOPASDFGHJKLZXCCVBMN&quot;;
 for(int i = 0; i < length; i++)
 {
 builder.Append(abc[UnityEngine.Random.Range(0,abc.Length - 1)]);
 }
 return builder.ToString();
 }

 public static string Join<T>(T[] arr,string join = &quot;,&quot;)
 {
 if(arr == null || arr.Length == 0)
 return null;

 StringBuilder builder = new StringBuilder();
 for(int i = 0; i < arr.Length; i++)
 {
 builder.Append(arr[i]);
 if(i < arr.Length - 1)
 builder.Append(join);
 }
 return builder.ToString();
 }

 /// <summary>
 ///  Chinese comma to English comma
 /// </summary>
 /// <param name=&quot;input&quot;></param>
 /// <returns></returns>
 public static string ToDBC(string input)
 {
 char[] c = input.ToCharArray();
 for(int i = 0; i < c.Length; i++)
 {
 if(c[i] == 12288)
 {
 c[i] = (char)32;
 continue;
 }
 if(c[i] > 65280 && c[i] < 65375)
 c[i] = (char)(c[i] - 65248);
 }
 return new string(c);
 }

 /// <summary>
 ///  Character conversion  ascii  code  
 /// </summary>
 /// <param name=&quot;character&quot;></param>
 /// <returns></returns>
 public static int Asc(string character)
 {
 if(character.Length == 1)
 {
 System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
 int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
 return (intAsciiCode);
 }
 Debug.LogError(&quot;Character is not valid.&quot;);
 return -1;
 }

 /// <summary>
 /// ascii Code to character
 /// </summary>
 /// <param name=&quot;asciiCode&quot;></param>
 /// <returns></returns>
 public static string Chr(int asciiCode)
 {
 if(asciiCode >= 0 && asciiCode <= 255)
 {
 System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
 byte[] byteArray = new byte[] { (byte)asciiCode };
 string strCharacter = asciiEncoding.GetString(byteArray);
 return (strCharacter);
 }
 Debug.LogError(&quot;ASCII Code is not valid.&quot;);
 return string.Empty;
 }

 /// <summary>
 ///  Filter out emoticons
 /// </summary>
 /// <returns>The emoji.</returns>
 /// <param name=&quot;str&quot;>String.</param>
 public static string FilterEmoji(string str)
 {
 List<string> patten = new List<string>() { @&quot;\p{Cs}&quot;,@&quot;\p{Co}&quot;,@&quot;\p{Cn}&quot;,@&quot;[\u2702-\u27B0]&quot; };
 for(int i = 0; i < patten.Count; i++)
 {
 str = Regex.Replace(str,patten[i],&quot;&quot;);// shielding emoji 
 }
 return str;
 }

 /// <summary>
 ///  Filter out emoticons
 /// </summary>
 /// <returns>The emoji.</returns>
 /// <param name=&quot;str&quot;>String.</param>
 public static bool IsFilterEmoji(string str)
 {
 bool bEmoji = false;
 List<string> patten = new List<string>() { @&quot;\p{Cs}&quot;,@&quot;\p{Co}&quot;,@&quot;\p{Cn}&quot;,@&quot;[\u2702-\u27B0]&quot; };
 for(int i = 0; i < patten.Count; i++)
 {
 bEmoji = Regex.IsMatch(str,patten[i]);
 if(bEmoji)
 {
 break;
 }
 }
 return bEmoji;
 }

 #endregion

 #region StringObjectDictionaryExtensions

 /// <summary>
 ///  Structure for the following key values contained in the dictionary :mctid0=xxx;mccount0=1,mctid1=kn2,mccount=2. Remove the prefix , The number suffix becomes a key , Such as { suffix ,( Remove the key before the suffix , value )}, Note that the suffix may be an empty string, that is, there is no suffix
 /// </summary>
 /// <param name=&quot;dic&quot;></param>
 /// <param name=&quot;prefix&quot;> Prefix , It can be an empty reference or an empty string , Means there is no prefix .</param>
 [MethodImpl(MethodImplOptions.AggressiveInlining)]
 public static IEnumerable<IGrouping<string,(string, object)>> GetValuesWithoutPrefix(this IReadOnlyDictionary<string,object> dic,string prefix = null)
 {
 //prefix ??= string.Empty;
 prefix = prefix ?? string.Empty;

 var coll = from tmp in dic.Where(c => c.Key.StartsWith(prefix)) // Only for the key value of the specified prefix
 let p3 = tmp.Key.Get3Segment(prefix)
 group (p3.Item2, tmp.Value) by p3.Item3;
 return coll;
 }

 /// <summary>
 ///  Break the string into three segments , Prefix , Root , number suffix ( String form ).
 /// </summary>
 /// <param name=&quot;str&quot;></param>
 /// <param name=&quot;prefix&quot;> Prefix , It can be an empty reference or an empty string , Means there is no prefix .</param>
 /// <returns></returns>
 [MethodImpl(MethodImplOptions.AggressiveInlining)]
 public static (string, string, string) Get3Segment(this string str,string prefix = null)
 {
 //prefix ??= string.Empty;
 prefix = prefix ?? string.Empty;

 // The length of the last decimal digit tail string
 int suffixLen = Enumerable.Reverse(str).TakeWhile(c => char.IsDigit(c)).Count();
 // Get decimal digit suffix
 //string suufix = str[^suffixLen..]; //^suffixLen: Reverse subscript ;suffixLen..: From the specified position to the end
 string suufix = str.Substring(str.Length - suffixLen);

 //return (prefix, str[prefix.Length..^suufix.Length], suufix);
 string middle = str.Substring(prefix.Length,str.Length - prefix.Length - suufix.Length);
 return (prefix, middle, suufix);
 }

 #endregion

}

Demo link :

https://download.csdn.net/download/qq_39108767/85913988
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061532510081.html