赞
踩
在游戏制作用,UI的代码架构是固定的。为了快速开发,只需要获得一个完整的UI结构代码,然后编写对应的业务逻辑即可。所以,自动化生成模板代码是一件必不可少的事情。
UI的架构通常使用MVC的结构,这次就演示V的生成,其他模板的生成流程其实也大同小异。代码就不加功能了,重点放到生成代码上面去。
public class TempletView { public const string Name = "TempletView"; public GameObject m_GameObject = null; public Transform m_Transform = null; public void OnInit(GameObject root) { m_GameObject = root; m_Transform = m_GameObject.transform; InitUI(); } } private void InitUI() { //Start //End }
StringBuilder codeStringBuilder = new StringBuilder(); using(StreamReader reader = File.OpenText(TempletViewPath) { string lineReader = string.Empty; while ((lineReader = reader.ReadLine()) != null) { if(lineReader .Contains("TempletView ") { lineReader = lineReader.replace("TempletView",prefabName); } codeStringBuilder. Append(lineReader); if(lineReader.Contains("Transform m_Transform") { for(int index = 0;index<Components.count;index++) { codeStringBuilder.Append($"m_{Components[index].name}_{Components[index].getType().Name} = null;\n"); } } if(lineReader.Contains("Start") { for(int index = 0;index<Components.count;index++) { codeStringBuilder.Append($"m_{Components[index].name}_{Components[index].getType().Name} = m_Transform.Find("{Components[index].name}").gameobject.GetComponent<{Components[index].getType().Name}>();\n"); } } } } if(codeStringBuilder.Length>0) { StreamWriter writter = File.CreateText(UIFilePath); writter.Write(codeStringBuilder.toString()); writter.Close(); }
StringBuilder codeStringBuilder = new StringBuilder(); using(StreamReader reader = File.OpenText(UIFilePath) { string lineReader = string.Empty; bool replace =false; while ((lineReader = reader.ReadLine()) != null) { if(!replace) { codeStringBuilder. Append(lineReader); } if(lineReader.Contains("Start") || lineReader.Contains("Transform m_Transform")) { replace = true; } if(lineReader.Contains("void OnInit")) { replace = false; for(int index = 0;index<Components.count;index++) { codeStringBuilder.Append($"m_{Components[index].name}_{Components[index].getType().Name} = null;\n"); } codeStringBuilder.Append("\n\n"); codeStringBuilder.Append(lineReader); } if(lineReader.Contains("End") { replace = false; for(int index = 0;index<Components.count;index++) { codeStringBuilder.Append($"m_{Components[index].name}_{Components[index].getType().Name} = m_Transform.Find("{Components[index].name}").gameobject.GetComponent<{Components[index].getType().Name}>();"); } codeStringBuilder.Append(lineReader); } } } if(codeStringBuilder.Length>0) { StreamWriter writter = File.CreateText(UIFilePath); writter.Write(codeStringBuilder.toString()); writter.Close(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。