初始化

This commit is contained in:
come
2025-07-26 16:56:42 +08:00
parent 8291dbb91c
commit fa81439a8c
2574 changed files with 328492 additions and 2170 deletions

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b86f0c73d94b413988ec0aaedc62e686
timeCreated: 1682072802

View File

@@ -0,0 +1,23 @@
#if UNITY_EDITOR
using Sirenix.OdinInspector;
namespace YIUIFramework.Editor
{
/// <summary>
/// 基类 自动创建模块
/// 由其他模块继承后实现
/// </summary>
[HideReferenceObjectPicker]
public abstract class BaseCreateModule
{
public virtual void Initialize()
{
}
public virtual void OnDestroy()
{
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cfeab8e519934f158c7b54184d5af922
timeCreated: 1682072802

View File

@@ -0,0 +1,258 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YIUIFramework.Editor
{
public struct CreateVo
{
/// <summary>
/// 只能是.txt 的模板
/// 重写文件不需要模板
/// </summary>
public string TemplatePath;
/// <summary>
/// 文件保存的位置
/// </summary>
public string SavePath;
public CreateVo(string templatePath, string savePath)
{
TemplatePath = templatePath;
SavePath = savePath;
}
}
public abstract class BaseTemplate
{
/// <summary>
/// 这个模板动作的名称
/// 作用于提示信息
/// </summary>
public virtual string EventName => "";
protected CreateVo CreateVo;
//常规新文件用字典
protected Dictionary<string, string> ValueDic;
public BaseTemplate(string authorName)
{
var dt = DateTime.Now;
ValueDic = new Dictionary<string, string>();
ValueDic["Author"] = authorName;
ValueDic["CreateDate"] = $"{dt.Year}.{dt.Month}.{dt.Day}";
}
/// <summary>
/// 是否覆盖 如果存在的情况下
/// 写入新文件时可用
/// </summary>
public virtual bool Cover => true;
/// <summary>
/// 其他是否保留
/// 重写文件时可用
/// </summary>
public virtual bool OtherRetain => true;
/// <summary>
/// 如果值已存在是否跳过
/// 重写文件时可用
/// </summary>
public virtual bool ExistSkip => true;
/// <summary>
/// 完成后自动刷新
/// </summary>
public virtual bool AutoRefresh => true;
/// <summary>
/// 提示
/// </summary>
public virtual bool ShowTips => true;
/// <summary>
/// 根据模板创建一个新文件
/// </summary>
/// <returns></returns>
protected bool CreateNewFile()
{
if (TemplateEngine.FileExists(CreateVo.SavePath))
{
if (!Cover)
{
if (ShowTips)
{
var code = $"文件已存在 当前选择已存在不覆盖 {CreateVo.SavePath}";
Debug.LogError(code);
EditorUtility.DisplayDialog("提示", code, "确认");
}
return false;
}
}
if (!TemplateEngine.CreateCodeFile(CreateVo.SavePath, CreateVo.TemplatePath, ValueDic))
{
EditorUtility.DisplayDialog("提示", CreateVo.SavePath + "创建失败", "确认");
TemplateEngine.TemplateBasePath = null;
return false;
}
if (ShowTips)
{
EditorUtility.DisplayDialog("提示", $"{EventName} 处理完毕", "确认");
}
if (AutoRefresh)
{
AssetDatabase.Refresh();
}
return true;
}
/// <summary>
/// 重写文件
/// 指定区域内的都会被重写 不存在检查 是否重复的情况
/// 这种使用一般是这块区域就是固定的区域不允许玩家乱写的
/// </summary>
/// <returns></returns>
protected bool OverrideCodeFile()
{
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
if (ShowTips)
{
var code = $"文件不存在 无法重写 {CreateVo.SavePath}";
Debug.LogError(code);
EditorUtility.DisplayDialog("提示", code, "确认");
}
return false;
}
if (!TemplateEngine.OverrideCodeFile(CreateVo.SavePath, ValueDic, OtherRetain))
{
EditorUtility.DisplayDialog("提示", CreateVo.SavePath + "创建失败", "确认");
TemplateEngine.TemplateBasePath = null;
return false;
}
if (ShowTips)
{
EditorUtility.DisplayDialog("提示", $"{EventName} 处理完毕", "确认");
}
if (AutoRefresh)
{
AssetDatabase.Refresh();
}
return true;
}
/// <summary>
/// 区域内重写文件
/// 但是会检查 如果我要写的东西已经存在了就不写了
/// 如: 我要提供一个方法给玩家 如果这个方法已经存在了就不检查了 否则我就会创建一个新的方法
/// 使用此方法需要吧上面的 OverrideDic 赋值
/// </summary>
/// <returns></returns>
protected bool OverrideCheckCodeFile(Dictionary<string, List<Dictionary<string, string>>> overrideDic)
{
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
if (ShowTips)
{
var code = $"文件不存在 无法重写 {CreateVo.SavePath}";
Debug.LogError(code);
EditorUtility.DisplayDialog("提示", code, "确认");
}
return false;
}
if (overrideDic == null)
{
Debug.LogError("替换数据无值 无法操作 OverrideDic == null");
return false;
}
if (overrideDic.Count >= 1)
{
if (!TemplateEngine.OverrideCheckCodeFile(CreateVo.SavePath, overrideDic))
{
EditorUtility.DisplayDialog("提示", CreateVo.SavePath + "创建失败", "确认");
TemplateEngine.TemplateBasePath = null;
return false;
}
}
if (ShowTips)
{
EditorUtility.DisplayDialog("提示", $"{EventName} 处理完毕", "确认");
}
if (AutoRefresh)
{
AssetDatabase.Refresh();
}
return true;
}
}
/// <summary>
/// 这是一个案例 只需要new这个类 即可进行一系列模板操作
/// 创建一个新文件时
/// </summary>
public class TestTemplate : BaseTemplate
{
public override string EventName => "测试案例一 创建新文件";
public override bool Cover => false;
public TestTemplate(string authorName, string moduleName, string pkgName, string resName) : base(authorName)
{
CreateVo = new CreateVo(
"Assets/.../Template/BasePanelTemplate.txt",
$"Assets/../{moduleName}/UI/{resName}.cs");
ValueDic["moduleName"] = moduleName;
ValueDic["uiPkgName"] = pkgName;
ValueDic["uiResName"] = resName;
CreateNewFile();
}
}
/// <summary>
/// 这是一个案例 只需要new这个类 即可进行一系列模板操作
/// 重写文件内容
/// </summary>
public class TestTemplate2 : BaseTemplate
{
public override string EventName => "测试案例二 重写文件内容";
//public override bool OtherRetain => false;
public TestTemplate2(string authorName, string moduleName, string pkgName, string resName) : base(authorName)
{
CreateVo = new CreateVo(
"Assets/.../Template/BasePanelTemplate.txt",
$"Assets/../{moduleName}/UI/{resName}.cs");
ValueDic["moduleName"] = moduleName;
ValueDic["uiPkgName"] = pkgName;
ValueDic["uiResName"] = resName;
ValueDic["AA"] = "//我替换的东西"; //的相当于 标记为AA 这个范围内的所有东西都会被清空 替换我指定的内容
OverrideCodeFile();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f7bdf42418084424ae03d52c0f0f7054
timeCreated: 1682072802

View File

@@ -0,0 +1,81 @@
#if UNITY_EDITOR
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Serialization;
using Sirenix.Utilities.Editor;
using UnityEngine;
namespace YIUIFramework.Editor
{
[HideReferenceObjectPicker]
public abstract class BaseTreeMenuItem : BaseYIUIToolModule
{
private bool m_InitEnd;
protected BaseTreeMenuItem(OdinMenuEditorWindow autoTool, OdinMenuTree tree)
{
AutoTool = autoTool;
Tree = tree;
}
public override void SelectionMenu()
{
Init();
Select();
}
private void Init()
{
if (m_InitEnd) return;
Initialize();
m_InitEnd = true;
}
protected abstract void Select();
}
[HideReferenceObjectPicker]
public class TreeMenuItem<T> : BaseTreeMenuItem where T : BaseYIUIToolModule, new()
{
[ShowInInspector]
[HideLabel]
[HideReferenceObjectPicker]
public T Instance { get; internal set; }
public TreeMenuItem(OdinMenuEditorWindow autoTool, OdinMenuTree tree, string menuName, Texture icon) : base(autoTool,
tree)
{
Tree.Add(menuName, this, icon);
ModuleName = menuName;
}
public TreeMenuItem(OdinMenuEditorWindow autoTool, OdinMenuTree tree, string menuName, EditorIcon icon) : base(autoTool,
tree)
{
Tree.Add(menuName, this, icon);
ModuleName = menuName;
}
public override void Initialize()
{
Instance = new T
{
AutoTool = AutoTool,
Tree = Tree,
ModuleName = ModuleName,
};
Instance?.Initialize();
}
public override void OnDestroy()
{
Instance?.OnDestroy();
}
protected override void Select()
{
Instance?.SelectionMenu();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7f3c764c80144560912d8b94b49cae88
timeCreated: 1687313986

View File

@@ -0,0 +1,25 @@
#if UNITY_EDITOR
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using UnityEngine;
namespace YIUIFramework.Editor
{
[HideReferenceObjectPicker]
public class BaseYIUIToolModule : BaseCreateModule
{
[HideInInspector]
public OdinMenuEditorWindow AutoTool { get; internal set; }
[HideInInspector]
public OdinMenuTree Tree { get; internal set; }
[HideInInspector]
public string ModuleName { get; internal set; }
public virtual void SelectionMenu()
{
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b1bec234919e457d8aeed77ba912acc2
timeCreated: 1687314924

View File

@@ -0,0 +1,333 @@
#if UNITY_EDITOR
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace YIUIFramework.Editor
{
/// <summary>
/// 编辑器工具可能会用到的各种工具
/// </summary>
public static class EditorHelper
{
/// <summary>
/// 得到对应dll名字内所有type的集合
/// 例: GetTypesByAssembly("Framework.dll")
/// </summary>
/// <param name="assemblyNames"></param>
/// <returns></returns>
public static Type[] GetTypesByAssemblyName(params string[] assemblyNames)
{
return AppDomain.CurrentDomain.GetTypesByAssemblyName(assemblyNames);
}
/// <summary>
/// 执行批处理文件
/// </summary>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="openFolder"></param>
public static void DoBat(string path, string param = null, string openFolder = null)
{
try
{
if (string.IsNullOrEmpty(param))
{
Process.Start(GetProjPath(path));
}
else
{
Process.Start(GetProjPath(path), param);
}
if (openFolder != null)
{
OpenFileOrFolder(GetProjPath(openFolder));
}
}
catch (Exception ex)
{
Debug.Log(ex.ToString());
}
}
/// <summary>
/// 打开文件或文件夹
/// </summary>
/// <param name="path"></param>
public static void OpenFileOrFolder(string path)
{
Process.Start("explorer.exe", path.Replace("/", "\\"));
}
/// <summary>
/// 得到项目绝对路径
/// eg:
/// GetProjPath("") //out: "E:/project/igg/col3/UnityProjectWithDll"
/// GetProjPath("Assets") //out: "E:/project/igg/col3/UnityProjectWithDll/Assets"
/// </summary>
/// <returns></returns>
public static string GetProjPath(string relativePath = "")
{
if (relativePath == null)
{
relativePath = "";
}
relativePath = relativePath.Trim();
if (!string.IsNullOrEmpty(relativePath))
{
if (relativePath.Contains("\\"))
{
relativePath = relativePath.Replace("\\", "/");
}
if (!relativePath.StartsWith("/"))
{
relativePath = "/" + relativePath;
}
}
string projFolder = Application.dataPath;
return projFolder.Substring(0, projFolder.Length - 7) + relativePath;
}
public static Type[] GetTypesByInterface(string fullName)
{
return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a =>
{
return a.GetTypes().Where(t => GetInterfaceByName(t, fullName) != null);
}).ToArray();
}
public static Type GetInterfaceByName(Type type, string fullName)
{
var interfaces = type.GetInterfaces();
if (interfaces.Length < 1)
{
return null;
}
foreach (Type interfaceType in interfaces)
{
if (interfaceType.FullName != null && interfaceType.FullName.StartsWith(fullName))
{
return interfaceType;
}
}
return null;
}
public static string PlatformName
{
get
{
string platformName = "";
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.Android:
platformName = "Android";
break;
case BuildTarget.iOS:
platformName = "iOS";
break;
default:
platformName = "Windows";
break;
}
return platformName;
}
}
/// <summary>
/// 用于查找某个只知道名字的文件在什么位置
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string[] GetAssetPaths(string name)
{
var paths = AssetDatabase.FindAssets(name);
for (int i = 0; i < paths.Length; i++)
{
paths[i] = AssetDatabase.GUIDToAssetPath(paths[i]);
}
return paths;
}
/// <summary>
/// 在项目文件内写入文件
/// </summary>
public static bool WriteAllText(string path, string contents, bool log = false)
{
try
{
path = GetProjPath(path);
var dir = Path.GetDirectoryName(path);
if (dir == null)
{
Debug.LogError("dir == null");
return false;
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(path, contents, Encoding.UTF8);
if (log)
Debug.Log(path + "创建成功");
return true;
}
catch (Exception e)
{
Debug.LogError("写入文件失败: path =" + path + ", err=" + e);
return false;
}
}
public static string ReadAllText(string path)
{
try
{
path = GetProjPath(path);
if (!File.Exists(path))
{
return null;
}
return File.ReadAllText(path);
}
catch (Exception e)
{
Debug.LogError("读取文件失败: path =" + path + ", err=" + e);
return null;
}
}
public static bool WriteAllBytes(string path, byte[] bytes, bool log = false)
{
try
{
path = GetProjPath(path);
var dir = Path.GetDirectoryName(path);
if (dir == null)
{
Debug.LogError("dir == null");
return false;
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllBytes(path, bytes);
if (log)
Debug.Log(path + "创建成功");
return true;
}
catch (Exception e)
{
Debug.LogError("写入文件失败: path =" + path + ", err=" + e);
return false;
}
}
public static byte[] ReadAllBytes(string path)
{
try
{
path = GetProjPath(path);
if (!File.Exists(path))
{
return null;
}
return File.ReadAllBytes(path);
}
catch (Exception e)
{
Debug.LogError("读取文件失败: path =" + path + ", err=" + e);
return null;
}
}
/// <summary>
/// 是否忽略
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool IsFileIgnore(string path)
{
return path.EndsWith(".meta")
|| path.EndsWith(".manifest")
|| path.Contains(".DS_Store");
}
// ----------------------------------------------------------------------------------------
/// <summary>
/// 进度条界面更新
/// </summary>
/// <param name="title">标题</param>
/// <param name="message">内容</param>
/// <param name="current">当前进度</param>
/// <param name="total">总进度</param>
public static void DisplayProgressBar(string title, string message, int current, int total)
{
float progress = 0;
if (total != 0)
{
progress = Mathf.InverseLerp(0, total, current);
message = string.Format("{0} {1}/{2}", message, current + 1, total);
}
EditorUtility.DisplayProgressBar(title, message, progress);
}
/// <summary>
/// 关闭进度
/// </summary>
public static void ClearProgressBar()
{
EditorUtility.ClearProgressBar();
}
//检查目标路径文件夹是否存在
public static bool ExistsDirectory(string path)
{
return Directory.Exists(GetProjPath(path));
}
//检查文件夹 不存在则创建
public static void CreateExistsDirectory(string path, bool checkDirectory = false)
{
path = GetProjPath(path);
if (checkDirectory)
{
path = Path.GetDirectoryName(path);
if (path == null)
{
Debug.LogError($" {path} dir == null");
return;
}
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b348c4e9679e4b238dd2840884fafdd7
timeCreated: 1682072802

View File

@@ -0,0 +1,453 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace YIUIFramework.Editor
{
/// <summary>
/// 简单的模板引擎, 主要用在编辑器上
/// </summary>
public class TemplateEngine
{
private static readonly Dictionary<string, string> g_templateCacheMap = new Dictionary<string, string>();
/// <summary>
/// 模板文件的基础路径
/// eg: Assets/Ediotr/Config/Decoder/Template/
/// 注意: 前面不要“/”,后央要“/”
/// </summary>
public static string TemplateBasePath;
private const string m_StartSignFormat = "#region {0}开始";
private const string m_EndSignFormat = "#endregion {0}结束";
/// <summary>
/// 处理模板
/// </summary>
/// <param name="templatePath"></param>
/// <param name="valueDic"></param>
/// <param name="valueDic2"></param>
/// <param name="readTemplateCache"></param>
/// <returns></returns>
public static string Do(string templatePath, Dictionary<string, string> valueDic,
Dictionary<string, string> valueDic2, bool readTemplateCache = true)
{
if (!string.IsNullOrEmpty(TemplateBasePath))
{
if (TemplateBasePath.Contains("Assets/") && templatePath.Contains("Assets/"))
{
templatePath = templatePath.Replace("Assets/", "");
}
templatePath = TemplateBasePath + templatePath;
}
string templateStr = null;
if (readTemplateCache)
{
g_templateCacheMap.TryGetValue(templatePath, out templateStr);
}
if (templateStr == null)
{
string path = EditorHelper.GetProjPath(templatePath);
try
{
templateStr = File.ReadAllText(path);
}
catch (Exception e)
{
Debug.LogError("读取文件失败: " + e);
return null;
}
g_templateCacheMap[templatePath] = templateStr;
}
if (valueDic != null)
{
foreach (KeyValuePair<string, string> pair in valueDic)
{
templateStr = templateStr.Replace("${" + pair.Key + "}", pair.Value);
}
}
if (valueDic2 != null)
{
foreach (KeyValuePair<string, string> pair in valueDic2)
{
templateStr = templateStr.Replace("${" + pair.Key + "}", pair.Value);
}
}
return templateStr;
}
/// <summary>
/// 处理列表类型模板
/// </summary>
/// <typeparam name="TItemType"></typeparam>
/// <param name="itemTemplateStr"></param>
/// <param name="list"></param>
/// <param name="fieldOrPropNames"></param>
/// <param name="afterProcessItem">后处理函数</param>
/// <returns></returns>
public static string DoList<TItemType>(string itemTemplateStr, TItemType[] list, string[] fieldOrPropNames,
Func<string, TItemType, string> afterProcessItem = null)
{
Type itemType = typeof(TItemType);
int len = list.Length;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
{
TItemType item = list[i];
string template = itemTemplateStr;
foreach (string name in fieldOrPropNames)
{
string tName = "${" + name + "}";
FieldInfo fi = itemType.GetField(name);
if (fi != null)
{
template = template.Replace(tName, fi.GetValue(item).ToString());
continue;
}
PropertyInfo pi = itemType.GetProperty(name);
if (pi == null)
{
Debug.LogWarning($"no {name} fields or attributes in the {itemType}");
continue;
}
template = template.Replace(tName, pi.GetValue(item, null).ToString());
}
if (afterProcessItem != null)
{
template = afterProcessItem(template, item);
}
sb.Append(template);
}
return sb.ToString();
}
/// <summary>
/// 检查目标文件是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool FileExists(string path)
{
try
{
path = path.Contains("Assets/") ? path : "Assets/" + path;
path = EditorHelper.GetProjPath(path);
return File.Exists(path);
}
catch (Exception e)
{
Debug.LogError("检查目标文件是否存在失败: path =" + path + ", err=" + e);
return false;
}
}
public static bool CreateCodeFile(string path, string templateName, Dictionary<string, string> valueDic)
{
templateName = templateName.Contains("Assets/") ? templateName : "Assets/" + templateName;
templateName = templateName.Contains(".txt") ? templateName : templateName + ".txt";
string clsStr = Do(templateName, valueDic, null, false);
if (clsStr == null)
{
Debug.LogError("模板转化失败, templateName:" + templateName);
return false;
}
try
{
path = path.Contains("Assets/") ? path : "Assets/" + path;
path = EditorHelper.GetProjPath(path);
string dir = Path.GetDirectoryName(path);
if (dir == null)
{
Debug.LogError("dir == null");
return false;
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(path, clsStr, Encoding.UTF8);
Debug.Log(path + "创建成功");
return true;
}
catch (Exception e)
{
Debug.LogError("创建代码文件失败: path =" + path + ", err=" + e);
return false;
}
}
/// <summary>
/// 使用Unity #region 为标识的替换规则
/// 在#region >> #endregion 这块区域内查找规则替换
/// </summary>
/// <param name="otherRetain">标记中的其他的是否保留</param>
/// <returns></returns>
private static bool RegionReplace(string path, KeyValuePair<string, string> pair, bool otherRetain = true)
{
//获取文件
if (path != null)
{
StringBuilder stringBuilder = new StringBuilder();
StreamReader streamReader = new StreamReader(path);
string line = streamReader.ReadLine();
bool isWrite = false; //标记中途是否检查到已经写入过这个字段 防止重复
string startStr = string.Format(m_StartSignFormat, pair.Key);
string endStr = string.Format(m_EndSignFormat, pair.Key);
while (line != null)
{
if (line.IndexOf(startStr) > -1)
{
isWrite = true;
stringBuilder.Append(line + "\n");
}
else if (line.IndexOf(endStr) > -1)
{
if (isWrite)
{
stringBuilder.Append($"{pair.Value}\n");
isWrite = false;
}
stringBuilder.Append(line + "\n");
}
else
{
if (isWrite)
{
if (line.IndexOf(pair.Value) > -1)
{
isWrite = false;
}
if (otherRetain)
{
stringBuilder.Append(line + "\n");
}
}
else
{
stringBuilder.Append(line + "\n");
}
}
line = streamReader.ReadLine();
}
streamReader.Close();
StreamWriter streamWriter = new StreamWriter(path);
streamWriter.Write(stringBuilder.ToString());
streamWriter.Close();
}
else
{
Debug.LogError($"没有读取到{path}文件,请检查是否生成");
return false;
}
return true;
}
/// <summary>
/// 重写文件
/// 根据标识的范围重写
/// </summary>
/// <param name="path">精准路径 Assets/ ... XX.CS(扩展名)</param>
/// <param name="valueDic">精准替换的范围与值</param>
/// <param name="otherRetain">范围内的是否保留 默认保留 否则会覆盖</param>
/// <returns></returns>
public static bool OverrideCodeFile(string path, Dictionary<string, string> valueDic, bool otherRetain = true)
{
path = path.Contains("Assets/") ? path : "Assets/" + path;
path = EditorHelper.GetProjPath(path);
foreach (var pair in valueDic)
{
if (!RegionReplace(path, pair, otherRetain))
{
return false;
}
}
return true;
}
/// <summary>
/// 指定区域内进行检查写入
/// 需要区域内不存在才写入
/// </summary>
private static bool RegionCheckReplace2(string path, string signKey, string checkContent, string valueContent,
bool otherRetain = true)
{
//获取文件
if (path != null)
{
StringBuilder stringBuilder = new StringBuilder();
StreamReader streamReader = new StreamReader(path);
string line = streamReader.ReadLine();
bool checkExist = false; //检查是否已经存在 如果已经存在则不重写 否则需要重写
bool isWrite = false; //标记中途是否检查到已经写入过这个字段 防止重复
string startStr = string.Format(m_StartSignFormat, signKey);
string endStr = string.Format(m_EndSignFormat, signKey);
while (line != null)
{
if (line.IndexOf(startStr) > -1)
{
isWrite = true;
stringBuilder.Append(line + "\n");
}
else if (line.IndexOf(endStr) > -1)
{
if (isWrite)
{
if (!checkExist)
{
stringBuilder.Append($"{valueContent}\n");
}
isWrite = false;
}
stringBuilder.Append(line + "\n");
}
else
{
if (isWrite)
{
if (line.IndexOf(checkContent) > -1)
{
checkExist = true;
}
if (otherRetain)
{
stringBuilder.Append(line + "\n");
}
}
else
{
stringBuilder.Append(line + "\n");
}
}
line = streamReader.ReadLine();
}
streamReader.Close();
StreamWriter streamWriter = new StreamWriter(path);
streamWriter.Write(stringBuilder.ToString());
streamWriter.Close();
}
else
{
Debug.LogError($"没有读取到{path}文件,请检查是否生成");
return false;
}
return true;
}
/// <summary>
/// 指定区域内进行检查写入
/// 需要区域内不存在才写入
/// </summary>
public static bool OverrideCheckCodeFile(string path,
Dictionary<string, List<Dictionary<string, string>>> replaceDic)
{
string clsStr = RegionCheckReplace(path, replaceDic);
if (clsStr == null)
{
Debug.LogError("模板转化失败, path:" + path);
return false;
}
try
{
path = path.Contains("Assets/") ? path : "Assets/" + path;
path = EditorHelper.GetProjPath(path);
string dir = Path.GetDirectoryName(path);
if (dir == null)
{
Debug.LogError("dir == null");
return false;
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(path, clsStr, Encoding.UTF8);
Debug.Log(path + "重写成功");
return true;
}
catch (Exception e)
{
Debug.LogError("重写文件失败: path =" + path + ", err=" + e);
return false;
}
}
/// <summary>
/// 指定区域内进行检查写入
/// 需要区域内不存在才写入
/// </summary>
private static string RegionCheckReplace(string path,
Dictionary<string, List<Dictionary<string, string>>> replaceDic)
{
var templateStr = File.ReadAllText(path);
foreach (var item in replaceDic)
{
var key = item.Key;
var valueList = item.Value;
foreach (var data in valueList)
{
foreach (var ovDic in data)
{
var check = ovDic.Key;
var content = ovDic.Value;
string startStr = string.Format(m_StartSignFormat, key);
string endStr = string.Format(m_EndSignFormat, key);
var startIndex = templateStr.IndexOf(startStr);
var endIndex = templateStr.IndexOf(endStr);
if (startIndex > -1 && endIndex > startIndex)
{
var tempStr = templateStr.Substring(startIndex, endIndex - startIndex);
if (tempStr.IndexOf(check) <= -1)
{
templateStr = templateStr.Insert(endIndex - 1, content);
}
}
}
}
}
return templateStr;
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 00764f38f6cb4f5581961ad7a095d592
timeCreated: 1682072802

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e09294af364e4e1faea270c926f2bf5a
timeCreated: 1682072802

View File

@@ -0,0 +1,22 @@
using YIUIFramework;
namespace YIUICodeGenerated
{
/// <summary>
/// 由YIUI工具自动创建 请勿手动修改
/// 用法: UIBindHelper.InternalGameGetUIBindVoFunc = YIUICodeGenerated.UIBindProvider.Get;
/// </summary>
public static class UIBindProvider
{
public static UIBindVo[] Get()
{
var BasePanel = typeof(BasePanel);
var BaseView = typeof(BaseView);
var BaseComponent = typeof(BaseComponent);
var list = new UIBindVo[${Count}];
${Content}
return list;
}
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a25f7befce96fe844bfa83d898bc405a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
${PanelViewEnum}
/// <summary>
/// 由YIUI工具自动创建 请勿手动修改
/// </summary>
public abstract class ${ResName}Base:${BaseClass}
{
public const string PkgName = "${PkgName}";
public const string ResName = "${ResName}";
${Variables}
protected sealed override void UIBind()
{
${UIBind}
}
protected sealed override void UnUIBind()
{
${UIUnBind}
}
${VirtualMethod}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: caac8cf83bc548129d3b3c4afd7f7d9d
timeCreated: 1682331049

View File

@@ -0,0 +1,52 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
#region 生命周期
protected override void Initialize()
{
Debug.Log($"${ResName} Initialize");
}
protected override void Start()
{
Debug.Log($"${ResName} Start");
}
protected override void OnEnable()
{
Debug.Log($"${ResName} OnEnable");
}
protected override void OnDisable()
{
Debug.Log($"${ResName} OnDisable");
}
protected override void OnDestroy()
{
Debug.Log($"${ResName} OnDestroy");
}
#endregion
#region Event开始
#endregion Event结束
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 12238d3c085d45b6bbbbb40d1648469c
timeCreated: 1683872468

View File

@@ -0,0 +1,23 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
#region Event开始
#endregion Event结束
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e72a3dde57eb45c29f8094fe470ba195
timeCreated: 1687766004

View File

@@ -0,0 +1,59 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
#region 生命周期
protected override void Initialize()
{
Debug.Log($"${ResName} Initialize");
}
protected override void Start()
{
Debug.Log($"${ResName} Start");
}
protected override void OnEnable()
{
Debug.Log($"${ResName} OnEnable");
}
protected override void OnDisable()
{
Debug.Log($"${ResName} OnDisable");
}
protected override void OnDestroy()
{
Debug.Log($"${ResName} OnDestroy");
}
protected override async UniTask<bool> OnOpen()
{
await UniTask.CompletedTask;
Debug.Log($"${ResName} OnOpen");
return true;
}
protected override async UniTask<bool> OnOpen(ParamVo param)
{
return await base.OnOpen(param);
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e5b53197a6284bcba9069c51e27dda06
timeCreated: 1687766052

View File

@@ -0,0 +1,19 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 07063168d2c0438786227126df5ebc77
timeCreated: 1687765972

View File

@@ -0,0 +1,64 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
#region 生命周期
protected override void Initialize()
{
Debug.Log($"${ResName} Initialize");
}
protected override void Start()
{
Debug.Log($"${ResName} Start");
}
protected override void OnEnable()
{
Debug.Log($"${ResName} OnEnable");
}
protected override void OnDisable()
{
Debug.Log($"${ResName} OnDisable");
}
protected override void OnDestroy()
{
Debug.Log($"${ResName} OnDestroy");
}
protected override async UniTask<bool> OnOpen()
{
await UniTask.CompletedTask;
Debug.Log($"${ResName} OnOpen");
return true;
}
protected override async UniTask<bool> OnOpen(ParamVo param)
{
return await base.OnOpen(param);
}
#endregion
#region Event开始
#endregion Event结束
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 72d669744369464f999a6b7962f9218f
timeCreated: 1682425924

View File

@@ -0,0 +1,16 @@
using Sirenix.OdinInspector;
namespace YIUIFramework
{
/// <summary>
/// 红点系统 所有key枚举
/// 由YIUI工具自动创建 请勿手动修改
/// </summary>
public enum ERedDotKeyType
{
[LabelText("无")]
None = 0,
${Content}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e88d92706f5748ada350a2fed78c04d2
timeCreated: 1686711524

View File

@@ -0,0 +1,64 @@
using System;
using YIUIBind;
using YIUIFramework;
using UnityEngine;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace ${Namespace}.${PkgName}
{
/// <summary>
/// Author ${Author}
/// Date ${CreateDate}
/// </summary>
public sealed partial class ${ResName}:${ResName}Base
{
#region 生命周期
protected override void Initialize()
{
Debug.Log($"${ResName} Initialize");
}
protected override void Start()
{
Debug.Log($"${ResName} Start");
}
protected override void OnEnable()
{
Debug.Log($"${ResName} OnEnable");
}
protected override void OnDisable()
{
Debug.Log($"${ResName} OnDisable");
}
protected override void OnDestroy()
{
Debug.Log($"${ResName} OnDestroy");
}
protected override async UniTask<bool> OnOpen()
{
await UniTask.CompletedTask;
Debug.Log($"${ResName} OnOpen");
return true;
}
protected override async UniTask<bool> OnOpen(ParamVo param)
{
return await base.OnOpen(param);
}
#endregion
#region Event开始
#endregion Event结束
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 05b0c9f335e1426f98d609ab085ed2f7
timeCreated: 1682427179

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cccf05fdce24462190e60388124c6627
timeCreated: 1682072802

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3dfa09fd43e848388276d9c43db382b8
timeCreated: 1682073471

View File

@@ -0,0 +1,16 @@
#if UNITY_EDITOR
using System;
using Sirenix.OdinInspector;
using UnityEngine;
namespace YIUIFramework.Editor
{
[HideReferenceObjectPicker]
public class CreateUIBaseEditorData
{
public CreateUIBaseEditorData()
{
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 857571c30a5d48a29f516b45a7ceb3b2
timeCreated: 1682073645

View File

@@ -0,0 +1,83 @@
#if UNITY_EDITOR
using System.IO;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using YIUIBind;
namespace YIUIFramework.Editor
{
/// <summary>
/// UIBase 模块
/// </summary>
[HideReferenceObjectPicker]
public class CreateUIBaseModule : BaseCreateModule
{
[LabelText("YIUI项目命名空间")]
[ShowInInspector]
[ReadOnly]
private const string UINamespace = UIStaticHelper.UINamespace;
[LabelText("YIUI项目资源路径")]
[FolderPath]
[ShowInInspector]
[ReadOnly]
private const string UIProjectResPath = UIStaticHelper.UIProjectResPath;
[LabelText("YIUI项目脚本路径")]
[FolderPath]
[ShowInInspector]
[ReadOnly]
private const string UIGenerationPath = UIStaticHelper.UIGenerationPath;
[LabelText("YIUI项目自定义脚本路径")]
[FolderPath]
[ShowInInspector]
[ReadOnly]
private const string UICodeScriptsPath = UIStaticHelper.UICodeScriptsPath;
[HideLabel]
[ShowInInspector]
private CreateUIBaseEditorData UIBaseData = new CreateUIBaseEditorData();
public override void Initialize()
{
}
public override void OnDestroy()
{
}
private const string m_CommonPkg = "Common";
[Button("初始化项目")]
private void CreateProject()
{
if (!UIOperationHelper.CheckUIOperation()) return;
EditorHelper.CreateExistsDirectory(UIGenerationPath);
EditorHelper.CreateExistsDirectory(UIProjectResPath);
EditorHelper.CreateExistsDirectory(UICodeScriptsPath);
UICreateResModule.Create(m_CommonPkg); //默认初始化一个common模块
CopyUIRoot();
YIUIAutoTool.CloseWindowRefresh();
}
private void CopyUIRoot()
{
var loadRoot = (GameObject)AssetDatabase.LoadAssetAtPath(UIStaticHelper.UIRootPrefabPath, typeof(Object));
if (loadRoot == null)
{
Debug.LogError($"没有找到原始UIRoot {UIStaticHelper.UIRootPrefabPath}");
return;
}
var newGameObj = Object.Instantiate(loadRoot);
var commonPath =
$"{UIProjectResPath}/{m_CommonPkg}/{UIStaticHelper.UIPrefabs}/{PanelMgr.UIRootName}.prefab";
PrefabUtility.SaveAsPrefabAsset(newGameObj, commonPath);
Object.DestroyImmediate(newGameObj);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6913ce2107d149458c075785522ace50
timeCreated: 1682073504

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 32a9ec9230724308bfe8c99f510bc0f5
timeCreated: 1682230391

View File

@@ -0,0 +1,32 @@
#if UNITY_EDITOR
using System;
using Sirenix.OdinInspector;
using UnityEngine;
namespace YIUIFramework.Editor
{
public class CreateUIBindProviderCode : BaseTemplate
{
public override string EventName => "UI反射动态码";
public override bool Cover => true;
public override bool AutoRefresh => true;
public override bool ShowTips => false;
public CreateUIBindProviderCode(out bool result, string authorName, UIBindProviderData codeData) : base(
authorName)
{
var path = $"{UIStaticHelper.UIGenerationPath}/{codeData.Name}.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UIBindProviderTemplate.txt";
CreateVo = new CreateVo(template, path);
ValueDic["Count"] = codeData.Count.ToString();
ValueDic["Content"] = codeData.Content;
result = CreateNewFile();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6c93b48396bb49119ba42b57ba2f4259
timeCreated: 1682231267

View File

@@ -0,0 +1,85 @@
using System;
using System.Collections;
using Sirenix.OdinInspector;
using YIUIBind;
using UnityEditor;
#if UNITY_EDITOR
using UnityEngine;
namespace YIUIFramework.Editor
{
/// <summary>
/// UI反射动态生成模板
/// </summary>
[HideReferenceObjectPicker]
public class CreateUIBindProviderModule : BaseCreateModule
{
[Button("UI自动生成绑定替代反射代码", 50), GUIColor(0.4f, 0.8f, 1)]
public void Create()
{
if (!UIOperationHelper.CheckUIOperation()) return;
var codeData = GenCodeByType(typeof(UIBindProvider));
if (codeData == null) return;
new CreateUIBindProviderCode(out var result, YIUIAutoTool.Author, codeData);
if (result)
{
UnityTipsHelper.CallBackOk("UI自动生成绑定替代反射代码 生成完毕", YIUIAutoTool.CloseWindowRefresh);
}
}
private static UIBindProviderData GenCodeByType(Type type)
{
var codeGenObj = Activator.CreateInstance(type);
var getFunInfo = type.GetMethod("Get");
if (getFunInfo == null)
{
Debug.LogError($"没有这个方法 Get");
return null;
}
var newFunInfo = type.GetMethod("NewCode");
if (newFunInfo == null)
{
Debug.LogError($"没有这个方法 NewCode");
return null;
}
var writeCodeFunInfo = type.GetMethod("WriteCode");
if (writeCodeFunInfo == null)
{
Debug.LogError($"没有这个方法 WriteCode");
return null;
}
var sb = SbPool.Get();
var list = (IList)getFunInfo.Invoke(codeGenObj, Array.Empty<object>());
for (int i = 0; i < list.Count; i++)
{
var data = list[i];
newFunInfo.Invoke(codeGenObj, new[] { data, sb });
sb.AppendFormat("\r list[{0}] = new {1}\r\n", i, data.GetType().Name);
writeCodeFunInfo.Invoke(codeGenObj, new[] { data, sb });
}
if (sb.Length > 2)
{
sb.Remove(sb.Length - 2, 2);
}
var userCode = SbPool.PutAndToStr(sb);
return new UIBindProviderData
{
Namespace = type.Namespace,
FullName = type.FullName,
Name = type.Name,
Count = list.Count,
Content = userCode,
};
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6535747a306143229e52def9ff17f765
timeCreated: 1682231112

View File

@@ -0,0 +1,14 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UIBindProviderData
{
public string Namespace;
public string FullName;
public string Name;
public int Count;
public string Content;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 74ad4ffc01ac42d380ab4eb63dbae575
timeCreated: 1682232084

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 215b2ed3aa9f4b969fc500d73e9697d9
timeCreated: 1682328201

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9ebb664457a64e75a90bd72a6a540174
timeCreated: 1682428309

View File

@@ -0,0 +1,41 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreateBaseCode : BaseTemplate
{
private string m_EventName = "UI核心代码创建";
public override string EventName => m_EventName;
public override bool Cover => true;
private bool m_AutoRefresh = false;
public override bool AutoRefresh => m_AutoRefresh;
private bool m_ShowTips = false;
public override bool ShowTips => m_ShowTips;
public UICreateBaseCode(out bool result, string authorName, UICreateBaseData codeData) : base(authorName)
{
var path = $"{UIStaticHelper.UIGenerationPath}/{codeData.PkgName}/{codeData.ResName}Base.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UICreateBaseTemplate.txt";
CreateVo = new CreateVo(template, path);
m_EventName = $"{codeData.ResName}Base 自动生成";
m_AutoRefresh = codeData.AutoRefresh;
m_ShowTips = codeData.ShowTips;
ValueDic["Namespace"] = codeData.Namespace;
ValueDic["PkgName"] = codeData.PkgName;
ValueDic["ResName"] = codeData.ResName;
ValueDic["BaseClass"] = codeData.BaseClass;
ValueDic["Variables"] = codeData.Variables;
ValueDic["UIBind"] = codeData.UIBind;
ValueDic["UIUnBind"] = codeData.UIUnBind;
ValueDic["VirtualMethod"] = codeData.VirtualMethod;
ValueDic["PanelViewEnum"] = codeData.PanelViewEnum;
result = CreateNewFile();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 39bdbec62df34ec9a7078313653b58e3
timeCreated: 1682331786

View File

@@ -0,0 +1,20 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreateBaseData
{
public bool AutoRefresh;
public bool ShowTips;
public string Namespace; //命名空间
public string PkgName; //包名/模块名
public string ResName; //资源名 类名+Base
public string BaseClass; //继承什么类 BasePanel/BaseView
public string Variables; //变量
public string UIBind; //绑定方法里面的东西
public string UIUnBind; //解绑里面的东西
public string VirtualMethod; //所有虚方法 Event里面的那些注册方法
public string PanelViewEnum; //枚举生成
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 760b99a79f234c23ada983fa838f6c58
timeCreated: 1682332177

View File

@@ -0,0 +1,125 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Text;
using YIUIBind;
using UnityEngine;
namespace YIUIFramework.Editor
{
/// <summary>
/// 绑定与解绑
/// </summary>
public static class UICreateBind
{
public static string GetBind(UIBindCDETable cdeTable)
{
var sb = SbPool.Get();
cdeTable.GetComponentTable(sb);
cdeTable.GetDataTable(sb);
cdeTable.GetEventTable(sb);
cdeTable.GetCDETable(sb);
return SbPool.PutAndToStr(sb);
}
private static void GetComponentTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.ComponentTable;
if (tab == null) return;
foreach (var value in tab.AllBindDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var bindCom = value.Value;
if (bindCom == null) continue;
sb.AppendFormat(" {1} = ComponentTable.FindComponent<{0}>(\"{1}\");\r\n", bindCom.GetType(),
name);
}
}
private static void GetDataTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.DataTable;
if (tab == null) return;
foreach (var value in tab.DataDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiData = value.Value;
var dataValue = uiData?.DataValue;
if (dataValue == null) continue;
sb.AppendFormat(" {1} = DataTable.FindDataValue<{0}>(\"{1}\");\r\n", dataValue.GetType(),
name);
}
}
private static void GetEventTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.EventTable;
if (tab == null) return;
foreach (var value in tab.EventDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiEventBase = value.Value;
if (uiEventBase == null) continue;
sb.AppendFormat(" {1} = EventTable.FindEvent<{0}>(\"{1}\");\r\n", uiEventBase.GetEventType(),
name);
sb.AppendFormat(" {0} = {1}.Add({2});\r\n", $"{name}Handle", name,
$"OnEvent{name.Replace($"{NameUtility.FirstName}{NameUtility.EventName}", "")}Action");
}
}
private static void GetCDETable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.AllChildCdeTable;
if (tab == null) return;
var existName = new HashSet<string>();
foreach (var value in tab)
{
var name = value.name;
if (string.IsNullOrEmpty(name)) continue;
var pkgName = value.PkgName;
var resName = value.ResName;
if (string.IsNullOrEmpty(resName)) continue;
var newName = UICreateVariables.GetCDEUIName(name);
if (existName.Contains(newName))
{
Debug.LogError($"{self.name} 内部公共组件存在同名 请修改 当前会被忽略");
continue;
}
existName.Add(newName);
sb.AppendFormat(" {0} = CDETable.FindUIBase<{1}>(\"{2}\");\r\n",
newName,
$"{UIStaticHelper.UINamespace}.{pkgName}.{resName}",
name);
}
}
public static string GetUnBind(UIBindCDETable cdeTable)
{
var sb = SbPool.Get();
cdeTable.GetUnEventTable(sb);
return SbPool.PutAndToStr(sb);
}
private static void GetUnEventTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.EventTable;
if (tab == null) return;
foreach (var value in tab.EventDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiEventBase = value.Value;
if (uiEventBase == null) continue;
sb.AppendFormat(" {0}.Remove({1});\r\n", name, $"{name}Handle");
}
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 64950beda6ea407380ad2eff44fa067a
timeCreated: 1682333900

View File

@@ -0,0 +1,113 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Text;
using YIUIBind;
namespace YIUIFramework.Editor
{
/// <summary>
/// 事件方法
/// </summary>
public static class UICreateMethod
{
public static string Get(UIBindCDETable cdeTable)
{
var sb = SbPool.Get();
cdeTable.GetEventTable(sb);
return SbPool.PutAndToStr(sb);
}
private static void GetEventTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.EventTable;
if (tab == null) return;
foreach (var value in tab.EventDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiEventBase = value.Value;
if (uiEventBase == null) continue;
if (uiEventBase.IsTaskEvent)
{
sb.AppendFormat(" protected virtual async UniTask {0}({1}){{await UniTask.CompletedTask;}}\r\n",
$"OnEvent{name.Replace($"{NameUtility.FirstName}{NameUtility.EventName}", "")}Action",
GetEventMethodParam(uiEventBase));
}
else
{
sb.AppendFormat(" protected virtual void {0}({1}){{}}\r\n",
$"OnEvent{name.Replace($"{NameUtility.FirstName}{NameUtility.EventName}", "")}Action",
GetEventMethodParam(uiEventBase));
}
}
}
private static string GetEventMethodParam(UIEventBase uiEventBase)
{
var paramCount = uiEventBase.AllEventParamType.Count;
if (paramCount <= 0)
{
return "";
}
var sb = SbPool.Get();
for (int i = 0; i < paramCount; i++)
{
var paramType = uiEventBase.AllEventParamType[i];
sb.AppendFormat("{0} p{1}", paramType.GetParamTypeString(), i + 1);
if (i < paramCount - 1)
{
sb.Append(",");
}
}
return SbPool.PutAndToStr(sb);
}
/// <summary>
/// 子类 帮助直接写上重写事件
/// </summary>
public static Dictionary<string, List<Dictionary<string, string>>> GetEventOverrideDic(UIBindCDETable cdeTable)
{
var overrideDic = new Dictionary<string, List<Dictionary<string, string>>>();
#region Event开始
var newList = new List<Dictionary<string, string>>();
overrideDic.Add("Event", newList);
var tab = cdeTable.EventTable;
if (tab == null) return null;
foreach (var value in tab.EventDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiEventBase = value.Value;
if (uiEventBase == null) continue;
var onEvent = $"OnEvent{name.Replace($"{NameUtility.FirstName}{NameUtility.EventName}", "")}";
var methodParam = $"Action({GetEventMethodParam(uiEventBase)})";
string check;
if (uiEventBase.IsTaskEvent)
check = $"protected override async UniTask {onEvent}{methodParam}";
else
check = $"protected override void {onEvent}{methodParam}";
var firstContent = $"\r\n {check}";
string content;
if (uiEventBase.IsTaskEvent)
content = firstContent + "\r\n {\r\n await UniTask.CompletedTask;\r\n }\r\n ";
else
content = firstContent + "\r\n {\r\n \r\n }\r\n ";
newList.Add(new Dictionary<string, string> { { check, content } });
}
#endregion Event结束
return overrideDic;
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f291dfef8d7d440fbca8b3bf7fc9d6d1
timeCreated: 1682333946

View File

@@ -0,0 +1,47 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using YIUIBind;
namespace YIUIFramework.Editor
{
/// <summary>
/// 界面的枚举
/// </summary>
public static class UICreatePanelViewEnum
{
public static string Get(UIBindCDETable cdeTable)
{
var sb = SbPool.Get();
cdeTable.GetEventTable(sb);
return SbPool.PutAndToStr(sb);
}
private static void GetEventTable(this UIBindCDETable self, StringBuilder sb)
{
var splitData = self.PanelSplitData;
if (splitData == null) return;
if (!splitData.ShowCreatePanelViewEnum()) return;
if (!splitData.CreatePanelViewEnum) return;
var index = 1;
sb.AppendFormat(" public enum E{0}ViewEnum\r\n {{\r\n", self.name);
AddViewEnum(splitData.AllCommonView, sb, ref index);
AddViewEnum(splitData.AllCreateView, sb, ref index);
AddViewEnum(splitData.AllPopupView, sb, ref index);
sb.Append(" }");
}
private static void AddViewEnum(List<RectTransform> viewList, StringBuilder sb, ref int index)
{
foreach (var viewParent in viewList)
{
var viewName = viewParent.name.Replace(UIStaticHelper.UIParentName, "");
sb.AppendFormat(" {0} = {1},\r\n", viewName, index);
index++;
}
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e713736c472742b7890b6c2608b019af
timeCreated: 1685690372

View File

@@ -0,0 +1,152 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using YIUIBind;
using UnityEngine;
namespace YIUIFramework.Editor
{
/// <summary>
/// 变量的生成
/// </summary>
public static class UICreateVariables
{
public static string Get(UIBindCDETable cdeTable)
{
var sb = SbPool.Get();
cdeTable.GetOverrideConfig(sb);
cdeTable.GetComponentTable(sb);
cdeTable.GetDataTable(sb);
cdeTable.GetCDETable(sb);
cdeTable.GetEventTable(sb);
return SbPool.PutAndToStr(sb);
}
private static void GetComponentTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.ComponentTable;
if (tab == null) return;
foreach (var value in tab.AllBindDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var bindCom = value.Value;
if (bindCom == null) continue;
sb.AppendFormat(" public {0} {1} {{ get; private set; }}\r\n", bindCom.GetType(), name);
}
}
private static void GetDataTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.DataTable;
if (tab == null) return;
foreach (var value in tab.DataDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiData = value.Value;
var dataValue = uiData?.DataValue;
if (dataValue == null) continue;
sb.AppendFormat(" public {0} {1} {{ get; private set; }}\r\n", dataValue.GetType(), name);
}
}
private static void GetEventTable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.EventTable;
if (tab == null) return;
foreach (var value in tab.EventDic)
{
var name = value.Key;
if (string.IsNullOrEmpty(name)) continue;
var uiEventBase = value.Value;
if (uiEventBase == null) continue;
sb.AppendFormat(" protected {0} {1} {{ get; private set; }}\r\n", uiEventBase.GetEventType(),
name);
sb.AppendFormat(" protected {0} {1} {{ get; private set; }}\r\n",
uiEventBase.GetEventHandleType(), $"{name}Handle");
}
}
private static void GetCDETable(this UIBindCDETable self, StringBuilder sb)
{
var tab = self.AllChildCdeTable;
if (tab == null) return;
var existName = new HashSet<string>();
foreach (var value in tab)
{
var name = value.name;
if (string.IsNullOrEmpty(name)) continue;
var pkgName = value.PkgName;
var resName = value.ResName;
if (string.IsNullOrEmpty(pkgName) || string.IsNullOrEmpty(resName)) continue;
var newName = GetCDEUIName(name);
if (existName.Contains(newName))
{
Debug.LogError($"{self.name} 内部公共组件存在同名 请修改 {name} 当前会被忽略 {newName}");
continue;
}
existName.Add(newName);
sb.AppendFormat(" public {0} {1} {{ get; private set; }}\r\n",
$"{UIStaticHelper.UINamespace}.{pkgName}.{resName}", newName);
}
}
internal static string GetCDEUIName(string oldName)
{
var newName = oldName;
if (!oldName.CheckFirstName(NameUtility.UIName))
{
newName = $"{NameUtility.FirstName}{NameUtility.UIName}{oldName}";
}
newName = Regex.Replace(newName, NameUtility.NameRegex, "");
return newName.ChangeToBigName(NameUtility.UIName);
}
private static void GetOverrideConfig(this UIBindCDETable self, StringBuilder sb)
{
switch (self.UICodeType)
{
case EUICodeType.Component:
return;
case EUICodeType.Panel:
sb.AppendFormat(" public override EWindowOption WindowOption => EWindowOption.{0};\r\n",
self.WindowOption.ToString().Replace(", ", "|EWindowOption."));
sb.AppendFormat(" public override EPanelLayer Layer => EPanelLayer.{0};\r\n",
self.PanelLayer);
sb.AppendFormat(" public override EPanelOption PanelOption => EPanelOption.{0};\r\n",
self.PanelOption.ToString().Replace(", ", "|EPanelOption."));
sb.AppendFormat(
" public override EPanelStackOption StackOption => EPanelStackOption.{0};\r\n",
self.PanelStackOption);
sb.AppendFormat(" public override int Priority => {0};\r\n", self.Priority);
if (self.PanelOption.HasFlag(EPanelOption.TimeCache))
sb.AppendFormat(" protected override float CachePanelTime => {0};\r\n\r\n",
self.CachePanelTime);
break;
case EUICodeType.View:
sb.AppendFormat(" public override EWindowOption WindowOption => EWindowOption.{0};\r\n",
self.WindowOption.ToString().Replace(", ", "|EWindowOption."));
sb.AppendFormat(
" public override EViewWindowType ViewWindowType => EViewWindowType.{0};\r\n",
self.ViewWindowType);
sb.AppendFormat(" public override EViewStackOption StackOption => EViewStackOption.{0};\r\n",
self.ViewStackOption);
break;
default:
Debug.LogError($"新增类型未实现 {self.UICodeType}");
break;
}
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3965c71fb6494dbbb112399b18d9a657
timeCreated: 1682333865

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d51c59f4206b447d8c42a6970a754633
timeCreated: 1683872143

View File

@@ -0,0 +1,47 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreateComponentCode : BaseTemplate
{
private string m_EventName = "UI继承Component代码创建";
public override string EventName => m_EventName;
public override bool Cover => false;
private bool m_AutoRefresh = false;
public override bool AutoRefresh => m_AutoRefresh;
private bool m_ShowTips = false;
public override bool ShowTips => m_ShowTips;
public UICreateComponentCode(out bool result, string authorName, UICreateComponentData codeData) : base(
authorName)
{
var path = $"{UIStaticHelper.UICodeScriptsPath}/{codeData.PkgName}/{codeData.ResName}.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UICreateComponentTemplate.txt";
CreateVo = new CreateVo(template, path);
m_EventName = $"{codeData.ResName} 继承 {codeData.ResName}Base 创建";
m_AutoRefresh = codeData.AutoRefresh;
m_ShowTips = codeData.ShowTips;
ValueDic["Namespace"] = codeData.Namespace;
ValueDic["PkgName"] = codeData.PkgName;
ValueDic["ResName"] = codeData.ResName;
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
result = CreateNewFile();
}
if (codeData.OverrideDic == null)
{
result = true;
return;
}
result = OverrideCheckCodeFile(codeData.OverrideDic);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 054645eb42ca48379662ab5f1a60ee91
timeCreated: 1683872290

View File

@@ -0,0 +1,16 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace YIUIFramework.Editor
{
public class UICreateComponentData
{
public bool AutoRefresh;
public bool ShowTips;
public string Namespace; //命名空间
public string PkgName; //包名/模块名
public string ResName; //资源名 类名+Base
public Dictionary<string, List<Dictionary<string, string>>> OverrideDic;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8d8d9e13b91947ed974fe0df5ead85d1
timeCreated: 1683872259

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0d7dff95ebf541558c1cff2bc7a71dd2
timeCreated: 1682428319

View File

@@ -0,0 +1,46 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreatePanelCode : BaseTemplate
{
private string m_EventName = "UI继承Panel代码创建";
public override string EventName => m_EventName;
public override bool Cover => false;
private bool m_AutoRefresh = false;
public override bool AutoRefresh => m_AutoRefresh;
private bool m_ShowTips = false;
public override bool ShowTips => m_ShowTips;
public UICreatePanelCode(out bool result, string authorName, UICreatePanelData codeData) : base(authorName)
{
var path = $"{UIStaticHelper.UICodeScriptsPath}/{codeData.PkgName}/{codeData.ResName}.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UICreatePanelTemplate.txt";
CreateVo = new CreateVo(template, path);
m_EventName = $"{codeData.ResName} 继承 {codeData.ResName}Base 创建";
m_AutoRefresh = codeData.AutoRefresh;
m_ShowTips = codeData.ShowTips;
ValueDic["Namespace"] = codeData.Namespace;
ValueDic["PkgName"] = codeData.PkgName;
ValueDic["ResName"] = codeData.ResName;
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
result = CreateNewFile();
}
if (codeData.OverrideDic == null)
{
result = true;
return;
}
result = OverrideCheckCodeFile(codeData.OverrideDic);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 755ffa83e0a249ce86ece485281f3c69
timeCreated: 1682426030

View File

@@ -0,0 +1,16 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace YIUIFramework.Editor
{
public class UICreatePanelData
{
public bool AutoRefresh;
public bool ShowTips;
public string Namespace; //命名空间
public string PkgName; //包名/模块名
public string ResName; //资源名 类名+Base
public Dictionary<string, List<Dictionary<string, string>>> OverrideDic;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 19c5e749b4f94577b07fec16b71f233d
timeCreated: 1682426063

View File

@@ -0,0 +1,267 @@
#if UNITY_EDITOR
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using YIUIBind;
using UnityEditor;
using UnityEngine;
namespace YIUIFramework.Editor
{
public static class UICreateModule
{
internal static void Create(UIBindCDETable cdeTable, bool refresh, bool tips)
{
if (!UIOperationHelper.CheckUIOperation()) return;
/*
//留在这里看的 方便以后查API
//当这个是个资源的时候 存在磁盘中
var is0 = UnityEditor.EditorUtility.IsPersistent(cdeTable);
//返回></para>如果对象是Prefab的一部分则为True/返回>Functionl
var is1= UnityEditor.PrefabUtility.IsPartOfAnyPrefab(cdeTable);
//</para> . 0如果对象是不能编辑的Prefab的一部分则为True
var is2= UnityEditor.PrefabUtility.IsPartOfImmutablePrefab(cdeTable);
//>如果给定对象是Model Prefab Asset或Model Prefab实例的一部分则返回true
var is3= UnityEditor.PrefabUtility.IsPartOfModelPrefab(cdeTable);
//<摘要></para>如果给定对象是预制资源的一部分则返回true
var is4= UnityEditor.PrefabUtility.IsPartOfPrefabAsset(cdeTable);
//摘要></para>如果给定对象是Prefab实例的一部分则返回true
var is5= UnityEditor.PrefabUtility.IsPartOfPrefabInstance(cdeTable);
//a>如果给定对象是常规预制实例或预制资源的一部分则返回true。</para>
var is6= UnityEditor.PrefabUtility.IsPartOfRegularPrefab(cdeTable);
//>如果给定对象是Prefab Variant资产或Prefab Variant实例的一部分则返回true。
var is7= UnityEditor.PrefabUtility.IsPartOfVariantPrefab(cdeTable);
//>如果给定对象是Prefab实例的一部分而不是资产的一部分则返回true。</pa
var is8= UnityEditor.PrefabUtility.IsPartOfNonAssetPrefabInstance(cdeTable);
//>这个对象是Prefab的一部分不能应用吗?
var is9= UnityEditor.PrefabUtility.IsPartOfPrefabThatCanBeAppliedTo(cdeTable);
*/
var checkInstance = PrefabUtility.IsPartOfPrefabInstance(cdeTable);
if (checkInstance)
{
UnityTipsHelper.ShowErrorContext(cdeTable, $"不能对实体进行操作 必须进入预制体编辑!!!");
return;
}
var checkAsset = PrefabUtility.IsPartOfPrefabAsset(cdeTable);
if (!checkAsset)
{
UnityTipsHelper.ShowErrorContext(cdeTable,
$"1: 必须是预制体 2: 不能在Hierarchy面板中使用 必须在Project面板下的预制体原件才能使用使用 ");
return;
}
if (!cdeTable.AutoCheck())
{
return;
}
var createBaseData = new UICreateBaseData
{
AutoRefresh = refresh,
ShowTips = tips,
Namespace = UIStaticHelper.UINamespace,
PkgName = cdeTable.PkgName,
ResName = cdeTable.ResName,
BaseClass = GetBaseClass(cdeTable),
Variables = UICreateVariables.Get(cdeTable),
UIBind = UICreateBind.GetBind(cdeTable),
UIUnBind = UICreateBind.GetUnBind(cdeTable),
VirtualMethod = UICreateMethod.Get(cdeTable),
PanelViewEnum = UICreatePanelViewEnum.Get(cdeTable),
};
new UICreateBaseCode(out var resultBase, YIUIAutoTool.Author, createBaseData);
if (!resultBase) return;
if (cdeTable.UICodeType == EUICodeType.Panel)
{
var createPanelData = new UICreatePanelData
{
AutoRefresh = refresh,
ShowTips = tips,
Namespace = UIStaticHelper.UINamespace,
PkgName = cdeTable.PkgName,
ResName = cdeTable.ResName,
OverrideDic = UICreateMethod.GetEventOverrideDic(cdeTable),
};
new UICreatePanelCode(out var result, YIUIAutoTool.Author, createPanelData);
if (!result) return;
}
else if (cdeTable.UICodeType == EUICodeType.View)
{
var createViewData = new UICreateViewData
{
AutoRefresh = refresh,
ShowTips = tips,
Namespace = UIStaticHelper.UINamespace,
PkgName = cdeTable.PkgName,
ResName = cdeTable.ResName,
OverrideDic = UICreateMethod.GetEventOverrideDic(cdeTable),
};
new UICreateViewCode(out var result, YIUIAutoTool.Author, createViewData);
if (!result) return;
}
else if (cdeTable.UICodeType == EUICodeType.Component)
{
var createComponentData = new UICreateComponentData //目前看上去3个DATA都一样 是特意设定的 以后可独立扩展
{
AutoRefresh = refresh,
ShowTips = tips,
Namespace = UIStaticHelper.UINamespace,
PkgName = cdeTable.PkgName,
ResName = cdeTable.ResName,
OverrideDic = UICreateMethod.GetEventOverrideDic(cdeTable),
};
new UICreateComponentCode(out var result, YIUIAutoTool.Author, createComponentData);
if (!result) return;
}
else
{
Debug.LogError($"是新增了 新类型嘛????? {cdeTable.UICodeType}");
}
AssetDatabase.Refresh();
}
private static string GetBaseClass(UIBindCDETable cdeTable)
{
switch (cdeTable.UICodeType)
{
case EUICodeType.Panel:
return UIStaticHelper.UIBasePanelName;
case EUICodeType.View:
return UIStaticHelper.UIBaseViewName;
case EUICodeType.Component:
return UIStaticHelper.UIBaseComponentName;
default:
Debug.LogError($"是否新增了类型????");
return UIStaticHelper.UIBaseName;
}
}
private static string GetRegionEvent(UIBindCDETable cdeTable)
{
if (cdeTable.EventTable == null || cdeTable.EventTable.EventDic == null)
return "";
return cdeTable.EventTable.EventDic.Count <= 0
? ""
: " #region Event开始\r\n\r\n #endregion Event结束";
}
internal static bool InitVoName(UIBindCDETable cdeTable)
{
var path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(cdeTable);
var pkgName = GetPkgName(path);
if (string.IsNullOrEmpty(pkgName))
{
UnityTipsHelper.ShowErrorContext(cdeTable,
$"没有找到模块名 请在预制体上使用 且 必须在指定的文件夹下才可使用 {UIStaticHelper.UIProjectResPath}");
return false;
}
cdeTable.PkgName = Regex.Replace(pkgName, NameUtility.NameRegex, "");
cdeTable.ResName = Regex.Replace(cdeTable.name, NameUtility.NameRegex, "");
if (cdeTable.ResName != cdeTable.name)
{
cdeTable.name = cdeTable.ResName;
AssetDatabase.RenameAsset(path, cdeTable.ResName);
}
return true;
}
private static string GetPkgName(string path, string currentName = "")
{
if (!path.Replace("\\", "/").Contains(UIStaticHelper.UIProjectResPath))
{
return null;
}
var parentInfo = System.IO.Directory.GetParent(path);
if (parentInfo == null)
{
return currentName;
}
if (parentInfo.Name == UIStaticHelper.UIProjectName)
{
return currentName;
}
return GetPkgName(parentInfo.FullName, parentInfo.Name);
}
//收集所有公共组件
internal static void RefreshChildCdeTable(UIBindCDETable cdeTable)
{
cdeTable.AllChildCdeTable.Clear();
AddCdeTable(ref cdeTable.AllChildCdeTable, cdeTable.transform);
CheckAddCdeTable(ref cdeTable.AllChildCdeTable, cdeTable);
}
//如果自己是panel 则还需要额外检查 是不是把自己的view给收集进去了
private static void CheckAddCdeTable(ref List<UIBindCDETable> addCdeTable, UIBindCDETable cdeTable)
{
if (cdeTable.UICodeType != EUICodeType.Panel && !cdeTable.IsSplitData)
return;
for (var i = addCdeTable.Count - 1; i >= 0; i--)
{
var targetTable = addCdeTable[i];
var parent = (RectTransform)targetTable.gameObject.transform.parent;
var parentName = parent.name;
//这里使用的是强判断 如果使用|| 可以弱判断根据需求 如果遵守View规则是没有问题的
if (parentName.Contains(UIStaticHelper.UIParentName) &&
parentName.Contains(targetTable.gameObject.name))
{
addCdeTable.RemoveAt(i);
}
}
}
private static void AddCdeTable(ref List<UIBindCDETable> cdeTable, Transform transform)
{
var childCount = transform.childCount;
if (childCount <= 0) return;
for (var i = childCount - 1; i >= 0; i--)
{
var child = transform.GetChild(i);
var childCde = child.GetComponent<UIBindCDETable>();
if (childCde == null)
{
AddCdeTable(ref cdeTable, child);
continue;
}
if (string.IsNullOrEmpty(childCde.PkgName) || string.IsNullOrEmpty(childCde.ResName)) continue;
if (childCde.UICodeType == EUICodeType.Panel)
{
Debug.LogError($"{transform.name} 公共组件嵌套了 其他面板 这是不允许的 {childCde.ResName} 已跳过忽略");
continue;
}
var newName = Regex.Replace(childCde.name, NameUtility.NameRegex, "");
if (childCde.name != newName)
{
childCde.name = newName;
}
cdeTable.Add(childCde);
}
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a3b1b934dd7940b090a1166b8d923139
timeCreated: 1682328185

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f75d69bf7253480db905368c012029ba
timeCreated: 1682428327

View File

@@ -0,0 +1,46 @@
#if UNITY_EDITOR
namespace YIUIFramework.Editor
{
public class UICreateViewCode : BaseTemplate
{
private string m_EventName = "UI继承View代码创建";
public override string EventName => m_EventName;
public override bool Cover => false;
private bool m_AutoRefresh = false;
public override bool AutoRefresh => m_AutoRefresh;
private bool m_ShowTips = false;
public override bool ShowTips => m_ShowTips;
public UICreateViewCode(out bool result, string authorName, UICreateViewData codeData) : base(authorName)
{
var path = $"{UIStaticHelper.UICodeScriptsPath}/{codeData.PkgName}/{codeData.ResName}.cs";
var template = $"{UIStaticHelper.UITemplatePath}/UICreateViewTemplate.txt";
CreateVo = new CreateVo(template, path);
m_EventName = $"{codeData.ResName} 继承 {codeData.ResName}Base 创建";
m_AutoRefresh = codeData.AutoRefresh;
m_ShowTips = codeData.ShowTips;
ValueDic["Namespace"] = codeData.Namespace;
ValueDic["PkgName"] = codeData.PkgName;
ValueDic["ResName"] = codeData.ResName;
if (!TemplateEngine.FileExists(CreateVo.SavePath))
{
result = CreateNewFile();
}
if (codeData.OverrideDic == null)
{
result = true;
return;
}
result = OverrideCheckCodeFile(codeData.OverrideDic);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 36610628a7594731a5600e71bf9a86f5
timeCreated: 1682428342

View File

@@ -0,0 +1,16 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace YIUIFramework.Editor
{
public class UICreateViewData
{
public bool AutoRefresh;
public bool ShowTips;
public string Namespace; //命名空间
public string PkgName; //包名/模块名
public string ResName; //资源名 类名+Base
public Dictionary<string, List<Dictionary<string, string>>> OverrideDic;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 93c6219dd08040c2a75b3fba80fc4e01
timeCreated: 1682428374

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 408505adbf074c1aa3fc680805476a48
timeCreated: 1686555609

View File

@@ -0,0 +1,282 @@
#if UNITY_EDITOR
using System;
using System.IO;
using System.Text;
using I2.Loc;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using YIUIBind;
namespace YIUIFramework.Editor
{
public class UII2LocalizationModule : BaseYIUIToolModule
{
private LanguageSourceData m_LanguageSourceData;
[LabelText("全数据名称")]
[ShowInInspector]
[ReadOnly]
public const string UII2SourceResName = "AllSource";
[LabelText("全数据保存路径")]
[FolderPath]
[ShowInInspector]
[ReadOnly]
public const string UII2SourceResPath = "Assets/Editor/I2Localization"; //这是编辑器下的数据 平台运行时 是不需要的
[LabelText("指定数据保存路径")]
[FolderPath]
[ShowInInspector]
[ReadOnly]
public const string UII2TargetLanguageResPath = "Assets/GameRes/I2Localization"; //运行时的资源是拆分的 根据需求加载
[Button("打开多语言数据", 50)]
[GUIColor(0.4f, 0.8f, 1)]
private void OpenI2Languages()
{
EditorApplication.ExecuteMenuItem("Tools/I2 Localization/Open I2Languages.asset");
}
[Button("导入", 50)]
[GUIColor(0f, 1f, 1f)]
private void ImportAllCsvTips()
{
UnityTipsHelper.CallBack("确认导入当前所有多语言数据吗\n\n此操作将会覆盖现有数据\n\n请确认", ImportAllCsv);
}
[Button("导出", 50)]
[GUIColor(0f, 1f, 1f)]
private void ExportAllCsvTips()
{
UnityTipsHelper.CallBack("确认导出当前所有多语言数据吗\n\n此操作将会覆盖现有数据\n\n请确认", ExportAllCsv);
}
#region
private string GetSourceResPath()
{
var projPath = EditorHelper.GetProjPath(UII2SourceResPath);
var path = $"{projPath}/{I2LocalizeHelper.I2ResAssetNamePrefix}{UII2SourceResName}.csv";
return path;
}
private void ExportAllCsv()
{
var editorAsset = LocalizationManager.GetEditorAsset(true);
m_LanguageSourceData = editorAsset?.SourceData;
if (m_LanguageSourceData == null)
{
UnityTipsHelper.ShowError($"没有找到多语言编辑器下的源数据 请检查 {I2LocalizeHelper.I2GlobalSourcesEditorPath}");
return;
}
var path = GetSourceResPath();
try
{
var content = Export_CSV(null);
File.WriteAllText(path, content, Encoding.UTF8);
}
catch (Exception e)
{
UnityTipsHelper.ShowError($"导出全数据时发生错误 请检查");
Debug.LogError(e);
return;
}
Debug.Log($"多语言 全数据 {UII2SourceResName} 导出CSV成功 {path}");
var projPath = EditorHelper.GetProjPath(UII2TargetLanguageResPath);
if (!Directory.Exists(projPath))
{
Directory.CreateDirectory(projPath);
}
foreach (var languages in m_LanguageSourceData.mLanguages)
{
var targetPath = "";
try
{
var content = Export_CSV(languages.Name);
targetPath = $"{projPath}/{I2LocalizeHelper.I2ResAssetNamePrefix}{languages.Name}.csv";
File.WriteAllText(targetPath, content, Encoding.UTF8);
}
catch (Exception e)
{
UnityTipsHelper.ShowError($"导出指定数据时发生错误 {languages.Name} 请检查 ");
Debug.LogError(e);
return;
}
Debug.Log($"多语言 指定数据 {languages.Name} 导出CSV成功 {targetPath}");
}
UnityTipsHelper.Show($"导出全数据完成 {path}");
YIUIAutoTool.CloseWindowRefresh();
}
#region
private string Export_CSV(string selectLanguage)
{
char Separator = ',';
var Builder = new StringBuilder();
var languages = m_LanguageSourceData.mLanguages;
var languagesCount = languages.Count;
Builder.AppendFormat("Key{0}Type{0}Desc", Separator);
var currentLanguageIndex = -1;
for (int i = 0; i < languagesCount; i++)
{
var langData = languages[i];
var currentLanguage = GoogleLanguages.GetCodedLanguage(langData.Name, langData.Code);
if (!string.IsNullOrEmpty(selectLanguage) && currentLanguage != selectLanguage)
{
continue;
}
Builder.Append(Separator);
if (!langData.IsEnabled())
Builder.Append('$');
AppendString(Builder, currentLanguage, Separator);
currentLanguageIndex = i;
}
if (string.IsNullOrEmpty(selectLanguage))
{
currentLanguageIndex = -1;
}
Builder.Append("\n");
var terms = m_LanguageSourceData.mTerms;
if (string.IsNullOrEmpty(selectLanguage))
{
terms.Sort((a, b) => string.CompareOrdinal(a.Term, b.Term));
}
foreach (var termData in terms)
{
var term = termData.Term;
foreach (var specialization in termData.GetAllSpecializations())
AppendTerm(Builder, currentLanguageIndex, term, termData, specialization, Separator);
}
return Builder.ToString();
}
private static void AppendTerm(StringBuilder Builder, int selectLanguageIndex, string Term, TermData termData,
string specialization, char Separator)
{
//--[ Key ] --------------
AppendString(Builder, Term, Separator);
if (!string.IsNullOrEmpty(specialization) && specialization != "Any")
Builder.AppendFormat("[{0}]", specialization);
//--[ Type and Description ] --------------
Builder.Append(Separator);
Builder.Append(termData.TermType.ToString());
Builder.Append(Separator);
AppendString(Builder, selectLanguageIndex <= -1 ? termData.Description : "", Separator);
var startIndex = selectLanguageIndex <= -1 ? 0 : selectLanguageIndex;
var maxIndex = selectLanguageIndex <= -1 ? termData.Languages.Length : selectLanguageIndex + 1;
//--[ Languages ] --------------
for (var i = startIndex; i < maxIndex; ++i)
{
Builder.Append(Separator);
var translation = termData.Languages[i];
if (!string.IsNullOrEmpty(specialization))
translation = termData.GetTranslation(i, specialization);
AppendTranslation(Builder, translation, Separator, null);
}
Builder.Append("\n");
}
private static void AppendString(StringBuilder Builder, string Text, char Separator)
{
if (string.IsNullOrEmpty(Text))
return;
Text = Text.Replace("\\n", "\n");
if (Text.IndexOfAny((Separator + "\n\"").ToCharArray()) >= 0)
{
Text = Text.Replace("\"", "\"\"");
Builder.AppendFormat("\"{0}\"", Text);
}
else
{
Builder.Append(Text);
}
}
private static void AppendTranslation(StringBuilder Builder, string Text, char Separator, string tags)
{
if (string.IsNullOrEmpty(Text))
return;
Text = Text.Replace("\\n", "\n");
if (Text.IndexOfAny((Separator + "\n\"").ToCharArray()) >= 0)
{
Text = Text.Replace("\"", "\"\"");
Builder.AppendFormat("\"{0}{1}\"", tags, Text);
}
else
{
Builder.Append(tags);
Builder.Append(Text);
}
}
#endregion
#endregion
#region
private void ImportAllCsv()
{
var editorAsset = LocalizationManager.GetEditorAsset(true);
m_LanguageSourceData = editorAsset?.SourceData;
if (m_LanguageSourceData == null)
{
UnityTipsHelper.ShowError($"没有找到多语言编辑器下的源数据 请检查 {I2LocalizeHelper.I2GlobalSourcesEditorPath}");
return;
}
var path = GetSourceResPath();
try
{
var content = LocalizationReader.ReadCSVfile(path, Encoding.UTF8);
var sError =
m_LanguageSourceData.Import_CSV(string.Empty, content, eSpreadsheetUpdateMode.Replace, ',');
if (!string.IsNullOrEmpty(sError))
UnityTipsHelper.ShowError($"导入全数据时发生错误 请检查 {sError} {path}");
}
catch (Exception e)
{
UnityTipsHelper.ShowError($"导入全数据时发生错误 请检查 {path}");
Debug.LogError(e);
return;
}
UnityTipsHelper.Show($"导入全数据完成 {path}");
YIUIAutoTool.CloseWindowRefresh();
}
#endregion
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: de07c2b4893247749335771bf2ee288b
timeCreated: 1686555698

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e81af26efeee481a9620653fe4c6d203
timeCreated: 1683538054

View File

@@ -0,0 +1,72 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEditor;
namespace YIUIFramework.Editor
{
[Serializable]
[HideLabel]
[HideReferenceObjectPicker]
public class MacroCurrentData
{
[LabelText("当前已存在宏数量")]
[ReadOnly]
public int CurrentMacroCount;
[LabelText("需要移除的宏")]
[ValueDropdown("GetValues")]
[InlineButton("Remove", "移除")]
public string RemoveMacro;
[LabelText("需要添加的宏")]
[InlineButton("Add", "添加")]
public string AddMacro;
private List<string> AllMacro;
//整个界面刷新 本来应该用通知的 这里偷懒直接回调了
//不会有其他需求了
private Action RefreshAction;
public MacroCurrentData(Action refreshAction)
{
RefreshAction = refreshAction;
RemoveMacro = null;
AddMacro = null;
AllMacro = MacroHelper.GetSymbols(UIMacroModule.BuildTargetGroup);
CurrentMacroCount = AllMacro.Count;
}
private IEnumerable<string> GetValues()
{
return AllMacro;
}
public void Add()
{
if (string.IsNullOrEmpty(AddMacro))
{
EditorUtility.DisplayDialog("提示", "请填写需要添加的宏名称", "确认");
return;
}
MacroHelper.AddMacro(AddMacro, UIMacroModule.BuildTargetGroup);
RefreshAction?.Invoke();
}
public void Remove()
{
if (string.IsNullOrEmpty(RemoveMacro))
{
EditorUtility.DisplayDialog("提示", "请选择需要移除的宏", "确认");
return;
}
MacroHelper.RemoveMacro(RemoveMacro, UIMacroModule.BuildTargetGroup);
RefreshAction?.Invoke();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6d51dc1161ad4cd9ab36683e1d9d0c01
timeCreated: 1683538145

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2b040d84346e41e7b430570dff4f0149
timeCreated: 1683538822

View File

@@ -0,0 +1,46 @@
#if UNITY_EDITOR
using System;
using Sirenix.OdinInspector;
namespace YIUIFramework.Editor
{
[Flags]
[LabelText("Test 测试")]
public enum ETestMacroType : long
{
[LabelText("所有")]
ALL = -1,
[LabelText("无")]
NONE = 0,
[LabelText("测试1")]
MACRO_TEST_1 = 1,
[LabelText("测试2")]
MACRO_TEST_2 = 1 << 1,
[LabelText("测试3")]
MACRO_TEST_3 = 1 << 2,
[LabelText("测试4")]
MACRO_TEST_4 = 1 << 3,
[LabelText("测试5")]
MACRO_TEST_5 = 1 << 4,
[LabelText("测试6")]
MACRO_TEST_6 = 1 << 5,
}
[Serializable]
public class TestMacroData : MacroDataBase<ETestMacroType>
{
protected override void Init()
{
MacroEnumType = (ETestMacroType)MacroHelper.InitEnumValue<ETestMacroType>(UIMacroModule.BuildTargetGroup);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b0ab127bbb704ae69260cf3c2d9b8276
timeCreated: 1683538860

View File

@@ -0,0 +1,43 @@
#if UNITY_EDITOR
using System;
using Sirenix.OdinInspector;
namespace YIUIFramework.Editor
{
[Flags]
[LabelText("YIUI")]
public enum EYIUIMacroType : long
{
[LabelText("所有")]
ALL = -1,
[LabelText("无")]
NONE = 0,
[LabelText("模拟非编辑器状态")]
YIUIMACRO_SIMULATE_NONEEDITOR = 1,
[LabelText("UIBing 初始化")]
YIUIMACRO_BIND_INITIALIZE = 1 << 1,
[LabelText("界面开关")]
YIUIMACRO_PANEL_OPENCLOSE = 1 << 2,
[LabelText("运行时调试UI")]
YIUIMACRO_BIND_RUNTIME_EDITOR = 1 << 3,
[LabelText("红点堆栈收集")]
YIUIMACRO_REDDOT_STACK = 1 << 4,
}
[Serializable]
public class UIMacroData : MacroDataBase<EYIUIMacroType>
{
protected override void Init()
{
MacroEnumType = (EYIUIMacroType)MacroHelper.InitEnumValue<EYIUIMacroType>(UIMacroModule.BuildTargetGroup);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3763caf3c1a24dbc826184577bcb00cd
timeCreated: 1683540809

View File

@@ -0,0 +1,65 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Sirenix.OdinInspector;
namespace YIUIFramework.Editor
{
[HideLabel]
[Serializable]
[HideReferenceObjectPicker]
public abstract class MacroDataBase
{
public void ResetMacro()
{
MacroHelper.RemoveMacro(GetAll(), UIMacroModule.BuildTargetGroup);
MacroHelper.AddMacro(GetSelect(), UIMacroModule.BuildTargetGroup);
}
public abstract List<string> GetAll();
public abstract List<string> GetSelect();
}
/// <summary>
/// 宏数据基类
/// </summary>
[HideLabel]
[HideReferenceObjectPicker]
[Serializable]
public abstract class MacroDataBase<T> : MacroDataBase where T : struct
{
[LabelText("宏 枚举")]
[ShowInInspector]
protected T MacroEnumType;
protected MacroDataBase()
{
Init();
}
/// <summary>
/// 初始化宏枚举值
/// </summary>
protected abstract void Init();
/// <summary>
/// 获取当前枚举所有宏
/// </summary>
/// <returns></returns>
public override List<string> GetAll()
{
return MacroHelper.GetEnumAll<T>();
}
/// <summary>
/// 获取选择宏
/// </summary>
/// <returns></returns>
public override List<string> GetSelect()
{
return MacroHelper.GetEnumSelect(MacroEnumType);
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 29cd40890639454d949d9aa18add478c
timeCreated: 1683538145

View File

@@ -0,0 +1,248 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YIUIFramework.Editor
{
/// <summary>
/// 宏助手
/// </summary>
public static class MacroHelper
{
public static List<string> GetSymbols(BuildTargetGroup targetGroup)
{
var ori = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
return new List<string>(ori.Split(';'));
}
public static void SetSymbols(List<string> defineSymbols,
BuildTargetGroup targetGroup)
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defineSymbols.ToArray()));
}
/// <summary>
/// 一次改变最终结果
/// 防止多次调用set
/// </summary>
public static void ChangeSymbols(List<string> allRemove, List<string> allSelect, BuildTargetGroup targetGroup)
{
var defineSymbols = GetSymbols(targetGroup);
for (int i = defineSymbols.Count - 1; i >= 0; i--)
{
var data = defineSymbols[i];
foreach (var remove in allRemove)
{
if (data == remove)
{
defineSymbols.Remove(data);
break;
}
}
}
foreach (var data in defineSymbols)
{
foreach (var add in allSelect)
{
if (data == add)
{
allSelect.Remove(add);
break;
}
}
}
defineSymbols.AddRange(allSelect);
SetSymbols(defineSymbols, targetGroup);
}
/// <summary>
/// 添加宏
/// </summary>
public static void AddMacro(string macro, BuildTargetGroup targetGroup)
{
if (string.IsNullOrEmpty(macro))
{
return;
}
var defineSymbols = GetSymbols(targetGroup);
foreach (var data in defineSymbols)
{
if (data == macro)
{
Debug.LogError($"此宏已存在 {macro}");
return;
}
}
defineSymbols.Add(macro);
SetSymbols(defineSymbols, targetGroup);
}
/// <summary>
/// 添加宏
/// </summary>
public static void AddMacro(List<string> macro, BuildTargetGroup targetGroup)
{
if (macro == null || macro.Count <= 0)
{
return;
}
var defineSymbols = GetSymbols(targetGroup);
foreach (var data in defineSymbols)
{
foreach (var add in macro)
{
if (data == add)
{
macro.Remove(add);
break;
}
}
}
defineSymbols.AddRange(macro);
SetSymbols(defineSymbols, targetGroup);
}
/// <summary>
/// 移除宏
/// </summary>
public static void RemoveMacro(string macro, BuildTargetGroup targetGroup)
{
if (string.IsNullOrEmpty(macro))
{
return;
}
var defineSymbols = GetSymbols(targetGroup);
foreach (var data in defineSymbols)
{
if (data == macro)
{
defineSymbols.Remove(data);
SetSymbols(defineSymbols, targetGroup);
return;
}
}
}
/// <summary>
/// 移除宏
/// </summary>
public static void RemoveMacro(List<string> macro, BuildTargetGroup targetGroup)
{
if (macro == null || macro.Count <= 0)
{
return;
}
var defineSymbols = GetSymbols(targetGroup);
for (int i = defineSymbols.Count - 1; i >= 0; i--)
{
var data = defineSymbols[i];
foreach (var remove in macro)
{
if (data == remove)
{
defineSymbols.Remove(data);
break;
}
}
}
SetSymbols(defineSymbols, targetGroup);
}
/// <summary>
/// 泛型 根据枚举获取所有字符串
/// </summary>
public static List<string> GetEnumAll<T>() where T : struct
{
var all = new List<string>();
foreach (var valueObj in Enum.GetValues(typeof(T)))
{
var value = (long)valueObj;
if (value <= 0)
{
continue;
}
all.Add(valueObj.ToString());
}
return all;
}
/// <summary>
/// 获取选择相同的
/// </summary>
public static List<string> GetEnumSelect<T>(T selectEnum) where T : struct
{
var selectValue = Convert.ToInt64(selectEnum);
;
var all = new List<string>();
foreach (var valueObj in Enum.GetValues(typeof(T)))
{
var value = (long)valueObj;
if (value <= 0)
{
continue;
}
if ((value & selectValue) != 0)
{
all.Add(valueObj.ToString());
}
}
return all;
}
/// <summary>
/// 根据现有宏 初始化枚举值
/// </summary>
public static long InitEnumValue<T>(BuildTargetGroup targetGroup) where T : struct
{
var defineSymbols = GetSymbols(targetGroup);
long initValue = 0;
foreach (var symbol in defineSymbols)
{
foreach (var valueObj in Enum.GetValues(typeof(T)))
{
var value = (long)valueObj;
if (value <= 0)
{
continue;
}
if (symbol == valueObj.ToString())
{
initValue += value;
}
}
}
return initValue;
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5510a1cfd1114d30a863fa60407f9287
timeCreated: 1683538145

View File

@@ -0,0 +1,104 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using YIUIBind;
namespace YIUIFramework.Editor
{
/// <summary>
/// 宏
/// </summary>
public class UIMacroModule : BaseYIUIToolModule
{
[GUIColor(0.4f, 0.8f, 1)]
[BoxGroup("目标平台切换", centerLabel: true)]
[OnValueChanged("OnBuildTargetGroupChange")]
[ShowInInspector]
[HideLabel]
public static BuildTargetGroup BuildTargetGroup = BuildTargetGroup.Standalone;
[BoxGroup("当前平台所有宏", centerLabel: true)]
[HideLabel]
public MacroCurrentData MacroStaticData;
[BoxGroup("自定义宏数据", centerLabel: true)]
[LabelText(" ")]
[ShowInInspector]
[ListDrawerSettings(IsReadOnly = true)]
[HideReferenceObjectPicker]
private List<MacroDataBase> AllMacroData;
[Button("更新自定义宏", 50), GUIColor(0.53f, 0.95f, 0.72f)]
public void Refresh()
{
if (!UIOperationHelper.CheckUIOperation()) return;
var allRemove = new List<string>();
var allSelect = new List<string>();
foreach (var macroData in AllMacroData)
{
allRemove.AddRange(macroData.GetAll());
allSelect.AddRange(macroData.GetSelect());
}
MacroHelper.ChangeSymbols(allRemove, allSelect, BuildTargetGroup);
SelfInitialize();
YIUIAutoTool.CloseWindowRefresh();
}
public override void Initialize()
{
BuildTargetGroup = GetCurrentBuildPlatform();
SelfInitialize();
}
private void SelfInitialize()
{
MacroStaticData = new MacroCurrentData(SelfInitialize);
AllMacroData = new List<MacroDataBase>
{
new UIMacroData(),
};
}
private static BuildTargetGroup GetCurrentBuildPlatform()
{
var buildTargetName = EditorUserBuildSettings.activeBuildTarget.ToString();
buildTargetName = buildTargetName.ToLower();
if (buildTargetName.IndexOf("standalone") >= 0)
{
return BuildTargetGroup.Standalone;
}
else if (buildTargetName.IndexOf("android") >= 0)
{
return BuildTargetGroup.Android;
}
else if (buildTargetName.IndexOf("iphone") >= 0)
{
return BuildTargetGroup.iOS;
}
else if (buildTargetName.IndexOf("ios") >= 0)
{
return BuildTargetGroup.iOS;
}
return BuildTargetGroup.Standalone;
}
private void OnBuildTargetGroupChange()
{
SelfInitialize();
}
public override void OnDestroy()
{
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c7e3f64b8e1c4cc5b200fe502ced1d5e
timeCreated: 1683538099

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8199f41582b248b8867c26c6d7556be8
timeCreated: 1682306165

View File

@@ -0,0 +1,222 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using Sirenix.OdinInspector;
using Sirenix.Serialization;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
namespace YIUIFramework.Editor
{
public enum EAtlasType
{
Master,
Variant,
}
public enum EPlatformType
{
[LabelText("默认")]
Default,
[LabelText("电脑")]
PC,
[LabelText("安卓")]
Android,
[LabelText("苹果")]
iPhone,
}
/// <summary>
/// 全局设置
/// </summary>
[HideReferenceObjectPicker]
[HideLabel]
public class UIAtlasModule : BaseCreateModule
{
[HideLabel]
public UISpriteAtlasSettings SpriteAtlasSettings = new UISpriteAtlasSettings();
[EnumToggleButtons]
[HideLabel]
[BoxGroup("平台设置", centerLabel: true)]
public EPlatformType m_UIPublishPackageData = EPlatformType.Default;
[HideInInspector]
public Dictionary<string, UIPlatformSettings> AllUIPlatformSettings =
new Dictionary<string, UIPlatformSettings>();
[ShowIf("m_UIPublishPackageData", EPlatformType.Default)]
[BoxGroup("平台设置", centerLabel: true)]
public UIPlatformSettings Default = new UIPlatformSettings
{
PlatformType = EPlatformType.Default,
BuildTargetName = "DefaultTexturePlatform",
Format = TextureImporterFormat.Automatic,
};
[ShowIf("m_UIPublishPackageData", EPlatformType.PC)]
[BoxGroup("平台设置", centerLabel: true)]
public UIPlatformSettings PC = new UIPlatformSettings
{
PlatformType = EPlatformType.PC,
BuildTargetName = "Standalone",
Format = TextureImporterFormat.DXT5Crunched,
};
[ShowIf("m_UIPublishPackageData", EPlatformType.Android)]
[BoxGroup("平台设置", centerLabel: true)]
public UIPlatformSettings Android = new UIPlatformSettings
{
PlatformType = EPlatformType.Android,
BuildTargetName = "Android",
Format = TextureImporterFormat.ASTC_6x6,
};
[ShowIf("m_UIPublishPackageData", EPlatformType.iPhone)]
[BoxGroup("平台设置", centerLabel: true)]
public UIPlatformSettings iPhone = new UIPlatformSettings
{
PlatformType = EPlatformType.iPhone,
BuildTargetName = "iPhone",
Format = TextureImporterFormat.ASTC_4x4,
};
private GlobalSpriteAtlasSettings m_GlobalSpriteAtlasSettings = new GlobalSpriteAtlasSettings();
public UIAtlasModule()
{
AllUIPlatformSettings.Add(Default.BuildTargetName, Default);
AllUIPlatformSettings.Add(PC.BuildTargetName, PC);
AllUIPlatformSettings.Add(Android.BuildTargetName, Android);
AllUIPlatformSettings.Add(iPhone.BuildTargetName, iPhone);
m_GlobalSpriteAtlasSettings.SpriteAtlasSettings = SpriteAtlasSettings;
m_GlobalSpriteAtlasSettings.Default = Default;
m_GlobalSpriteAtlasSettings.PC = PC;
m_GlobalSpriteAtlasSettings.Android = Android;
m_GlobalSpriteAtlasSettings.iPhone = iPhone;
}
private const string GlobalSaveSpriteAtlasSettingsPath =
UIStaticHelper.UIProjectEditorPath + "/GlobalSpriteAtlasSettings.txt";
private class GlobalSpriteAtlasSettings
{
public UISpriteAtlasSettings SpriteAtlasSettings;
public UIPlatformSettings Default;
public UIPlatformSettings PC;
public UIPlatformSettings Android;
public UIPlatformSettings iPhone;
}
public override void Initialize()
{
var data = OdinSerializationUtility.Load<GlobalSpriteAtlasSettings>(GlobalSaveSpriteAtlasSettingsPath);
if (data == null) return;
SpriteAtlasSettings = data.SpriteAtlasSettings;
Default = data.Default;
PC = data.PC;
Android = data.Android;
iPhone = data.iPhone;
}
public override void OnDestroy()
{
OdinSerializationUtility.Save(m_GlobalSpriteAtlasSettings, GlobalSaveSpriteAtlasSettingsPath);
}
public void ResetTargetBuildSetting(SpriteAtlas spriteAtlas)
{
spriteAtlas.SetIncludeInBuild(SpriteAtlasSettings.IncludeInBuild);
var packingSettings = new SpriteAtlasPackingSettings()
{
blockOffset = SpriteAtlasSettings.BlockOffset,
enableRotation = SpriteAtlasSettings.EnableRotation,
enableTightPacking = SpriteAtlasSettings.EnableTightPacking,
padding = SpriteAtlasSettings.Padding,
};
spriteAtlas.SetPackingSettings(packingSettings);
var textureSettings = new SpriteAtlasTextureSettings()
{
readable = SpriteAtlasSettings.Readable,
generateMipMaps = SpriteAtlasSettings.GenerateMipMaps,
sRGB = SpriteAtlasSettings.sRGB,
filterMode = SpriteAtlasSettings.FilterMode,
};
spriteAtlas.SetTextureSettings(textureSettings);
foreach (var targetSetting in AllUIPlatformSettings.Values)
{
var setting = spriteAtlas.GetPlatformSettings(targetSetting.BuildTargetName) ??
new TextureImporterPlatformSettings();
setting.overridden = targetSetting.Overridden;
setting.maxTextureSize = targetSetting.MaxTextureSize;
setting.crunchedCompression = targetSetting.CrunchedCompression;
setting.compressionQuality = targetSetting.compressionQuality;
setting.format = targetSetting.Format;
spriteAtlas.SetPlatformSettings(setting);
}
}
}
[HideReferenceObjectPicker]
[HideLabel]
public class UISpriteAtlasSettings
{
[ReadOnly]
public EAtlasType AtlasType = EAtlasType.Master;
public bool IncludeInBuild = true;
public int BlockOffset = 1;
public bool EnableRotation = false;
public bool EnableTightPacking = false;
[ValueDropdown("PaddingListKey")]
public int Padding = 4;
public bool GenerateMipMaps = false;
public bool Readable = false;
public bool sRGB = true;
public UnityEngine.FilterMode FilterMode = FilterMode.Bilinear;
private static List<int> PaddingListKey = new List<int> { 2, 4, 8 };
}
[HideReferenceObjectPicker]
[HideLabel]
public class UIPlatformSettings
{
[HideInInspector]
public EPlatformType PlatformType;
[HideInInspector]
public string BuildTargetName;
[HideIf("PlatformType", EPlatformType.Default)]
public bool Overridden = true;
[ValueDropdown("MaxTextureSizeListKey")]
public int MaxTextureSize = 2048;
private static List<int> MaxTextureSizeListKey = new List<int>
{
32, 64, 128, 256, 512, 1024, 2048, 4096, 8192
};
[ShowIf("PlatformType", EPlatformType.Default)]
public bool CrunchedCompression = true;
[Range(0, 100)]
public int compressionQuality = 50; // 0=Fast 50=Normal 100=Best 对应安卓IOS时
public TextureImporterFormat Format = TextureImporterFormat.Automatic;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2f33b8355c324f188dcb8c8ce43e7de6
timeCreated: 1683366588

View File

@@ -0,0 +1,56 @@
#if UNITY_EDITOR
using Sirenix.OdinInspector;
using UnityEditor;
using YIUIBind;
namespace YIUIFramework.Editor
{
[HideReferenceObjectPicker]
[HideLabel]
public class UICreateResModule : BaseCreateModule
{
[LabelText("新增模块名称")]
public string Name;
[GUIColor(0, 1, 0)]
[Button("创建", 30)]
private void Create()
{
if (!UIOperationHelper.CheckUIOperation()) return;
Create(Name);
}
public static void Create(string createName)
{
if (string.IsNullOrEmpty(createName))
{
UnityTipsHelper.ShowError("请设定 名称");
return;
}
createName = NameUtility.ToFirstUpper(createName);
var basePath = $"{UIStaticHelper.UIProjectResPath}/{createName}";
var prefabsPath = $"{basePath}/{UIStaticHelper.UIPrefabs}";
var spritesPath = $"{basePath}/{UIStaticHelper.UISprites}";
var spritesAtlas1Path = $"{basePath}/{UIStaticHelper.UISprites}/{UIStaticHelper.UISpritesAtlas1}";
var atlasIgnorePath = $"{basePath}/{UIStaticHelper.UISprites}/{UIStaticHelper.UIAtlasIgnore}";
var atlasPath = $"{basePath}/{UIStaticHelper.UIAtlas}";
var sourcePath = $"{basePath}/{UIStaticHelper.UISource}";
EditorHelper.CreateExistsDirectory(prefabsPath);
EditorHelper.CreateExistsDirectory(spritesPath);
EditorHelper.CreateExistsDirectory(spritesAtlas1Path);
EditorHelper.CreateExistsDirectory(atlasIgnorePath);
EditorHelper.CreateExistsDirectory(atlasPath);
EditorHelper.CreateExistsDirectory(sourcePath);
MenuItemYIUIPanel.CreateYIUIPanelByPath(sourcePath, createName);
YIUIAutoTool.CloseWindowRefresh();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1860166e36884c85a33a1f6ed4309e09
timeCreated: 1683346742

View File

@@ -0,0 +1,119 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities.Editor;
using YIUIBind;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
namespace YIUIFramework.Editor
{
public class UIPublishModule : BaseYIUIToolModule
{
internal const string m_PublishName = "发布";
[FolderPath]
[LabelText("所有模块资源路径")]
[ReadOnly]
[ShowInInspector]
private string m_AllPkgPath = UIStaticHelper.UIProjectResPath;
[BoxGroup("创建模块", centerLabel: true)]
[ShowInInspector]
internal UICreateResModule CreateResModule = new UICreateResModule();
//所有模块
private List<UIPublishPackageModule> m_AllUIPublishPackageModule = new List<UIPublishPackageModule>();
private void AddAllPkg()
{
EditorHelper.CreateExistsDirectory(m_AllPkgPath);
var folders = Array.Empty<string>();
try
{
folders = Directory.GetDirectories(EditorHelper.GetProjPath(m_AllPkgPath));
}
catch (Exception e)
{
Debug.LogError($"获取所有模块错误 请检查 err={e.Message}{e.StackTrace}");
return;
}
foreach (var folder in folders)
{
var pkgName = Path.GetFileName(folder);
var upperName = NameUtility.ToFirstUpper(pkgName);
if (upperName != pkgName)
{
Debug.LogError($"这是一个非法的模块[ {pkgName} ]请使用统一方法创建模块 或者满足指定要求");
continue;
}
var newUIPublishPackageModule = new UIPublishPackageModule(this, pkgName);
//0 模块
Tree.AddMenuItemAtPath(m_PublishName,
new OdinMenuItem(Tree, pkgName, newUIPublishPackageModule)).AddIcon(EditorIcons.Folder);
//1 图集
Tree.AddAllAssetsAtPath($"{m_PublishName}/{pkgName}/{UIStaticHelper.UIAtlasCN}",
$"{m_AllPkgPath}/{pkgName}/{UIStaticHelper.UIAtlas}", typeof(SpriteAtlas), true, false);
//2 预制体
Tree.AddAllAssetsAtPath($"{m_PublishName}/{pkgName}/{UIStaticHelper.UIPrefabsCN}",
$"{m_AllPkgPath}/{pkgName}/{UIStaticHelper.UIPrefabs}", typeof(UIBindCDETable), true, false);
//3 源文件
Tree.AddAllAssetsAtPath($"{m_PublishName}/{pkgName}/{UIStaticHelper.UISourceCN}",
$"{m_AllPkgPath}/{pkgName}/{UIStaticHelper.UISource}", typeof(UIBindCDETable), true, false);
//4 精灵
Tree.AddAllAssetImporterAtPath($"{m_PublishName}/{pkgName}/{UIStaticHelper.UISpritesCN}",
$"{m_AllPkgPath}/{pkgName}/{UIStaticHelper.UISprites}", typeof(TextureImporter), true, false);
m_AllUIPublishPackageModule.Add(newUIPublishPackageModule);
}
}
[GUIColor(0f, 1f, 1f)]
[Button("UI自动生成绑定替代反射代码", 50)]
[PropertyOrder(-9999)]
public static void CreateUIBindProvider()
{
new CreateUIBindProviderModule().Create();
}
[GUIColor(0.4f, 0.8f, 1)]
[Button("全部发布", 50)]
[PropertyOrder(-99)]
public void PublishAll()
{
if (!UIOperationHelper.CheckUIOperation()) return;
foreach (var module in m_AllUIPublishPackageModule)
{
module.PublishCurrent(false); //不要默认重置所有图集设置 有的图集真的会有独立设置
}
UnityTipsHelper.CallBackOk("YIUI全部 发布完毕", YIUIAutoTool.CloseWindowRefresh);
}
public override void Initialize()
{
AddAllPkg();
CreateResModule?.Initialize();
}
public override void OnDestroy()
{
CreateResModule?.OnDestroy();
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8b696239f96940859191ea3e3bc8054f
timeCreated: 1682306188

Some files were not shown because too many files have changed in this diff Show More