Skip to content

Commit 6f4baa6

Browse files
committed
feat(editor): 添加工厂方法并移除冗余 SerializeField 特性
为生成的 UGUI 组件添加 Create 和 GetFromPool 静态工厂方法, 支持对象池场景下复用组件;移除自动生成属性上的 SerializeField 特性,避免与 UGUIElementProperty 冲突。
1 parent b474fe6 commit 6f4baa6

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

Editor/UGUICodeGenerator.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,30 @@ private static string GenerateCode(GameObject selectedObject, string assetPath)
219219
PropertyHandler(selectedObject, null, nodeInfos, true);
220220
PropertyCodeHandler(codeBuilder, nodeInfos);
221221

222+
// 生成工厂方法
223+
codeBuilder.AppendLine($"\t\tpublic static {className} Create(GameObject go)");
224+
codeBuilder.AppendLine("\t\t{");
225+
codeBuilder.AppendLine("\t\t\tvar ui = go.GetOrAddComponent<" + className + ">();");
226+
codeBuilder.AppendLine("\t\t\tui?.InitView();");
227+
codeBuilder.AppendLine("\t\t\treturn ui;");
228+
codeBuilder.AppendLine("\t\t}");
229+
codeBuilder.AppendLine();
230+
codeBuilder.AppendLine("\t\t/// <summary>");
231+
codeBuilder.AppendLine("\t\t/// 通过此方法获取的UGUI,在Dispose时不会释放GameObject,需要自行管理(一般在配合对象池机制时使用)。");
232+
codeBuilder.AppendLine("\t\t/// </summary>");
233+
codeBuilder.AppendLine($"\t\tpublic static {className} GetFromPool(GameObject go)");
234+
codeBuilder.AppendLine("\t\t{");
235+
codeBuilder.AppendLine("\t\t\tvar ui = go.GetComponent<" + className + ">();");
236+
codeBuilder.AppendLine("\t\t\tif (ui == null)");
237+
codeBuilder.AppendLine("\t\t\t{");
238+
codeBuilder.AppendLine("\t\t\t\tui = Create(go);");
239+
codeBuilder.AppendLine("\t\t\t}");
240+
codeBuilder.AppendLine();
241+
codeBuilder.AppendLine("\t\t\tui.IsFromPool = true;");
242+
codeBuilder.AppendLine("\t\t\treturn ui;");
243+
codeBuilder.AppendLine("\t\t}");
244+
codeBuilder.AppendLine();
245+
222246
// 生成初始化方法
223247
codeBuilder.AppendLine("\t\tprivate bool _isInitView = false;");
224248
codeBuilder.AppendLine();
@@ -269,7 +293,7 @@ private static void PropertyCodeHandler(StringBuilder codeBuilder, List<NodeInfo
269293
foreach (var nodeInfo in nodeInfos)
270294
{
271295
string path = PathHandler(nodeInfo);
272-
codeBuilder.AppendLine($"\t\t[SerializeField] [UGUIElementProperty(\"{path}\")]");
296+
codeBuilder.AppendLine($"\t\t[UGUIElementProperty(\"{path}\")]");
273297
codeBuilder.AppendLine($"\t\tprivate {nodeInfo.Type} {nodeInfo.Name};");
274298
codeBuilder.AppendLine();
275299

0 commit comments

Comments
 (0)