public static string Generate(TextAsset template, VariableContainer variables) { if (template == null) { throw new ArgumentNullException("template"); } if (variables == null) { throw new ArgumentNullException("variables"); } string str = template.text; for (int i = 0; i < variables.Count; ++i) { str = str.Replace(variables[i].key, variables[i].value); } return(str); }
private void OnGUI() { using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope()) { template = EditorGUILayout.ObjectField("Template", template, typeof(TextAsset), false) as TextAsset; if (changeCheckScope.changed) { cachedVariables = CodeGenerator.ExtractVariables(template); } } if (GUILayout.Button("Open Template")) { AssetDatabase.OpenAsset(template); } GUILayout.Space(20); GUILayoutOption variableLayoutOption, replaceLayoutOption; GUIStyle boldLabelStyle = new GUIStyle(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleCenter }; if (CalculateLabelWidth(boldLabelStyle, 20, out float width)) { variableLayoutOption = GUILayout.Width(width); replaceLayoutOption = GUILayout.Width(position.width - width - 10); } else { variableLayoutOption = replaceLayoutOption = GUILayout.Width(position.width * 0.5f); } using (new EditorGUILayout.HorizontalScope()) { GUIStyle style = new GUIStyle(EditorStyles.toolbar) { alignment = TextAnchor.MiddleCenter }; EditorGUILayout.LabelField("Variable", style, variableLayoutOption); EditorGUILayout.LabelField("Replace", style, replaceLayoutOption); } if (cachedVariables != null) { for (int i = 0; i < cachedVariables.Count; ++i) { using (new EditorGUILayout.HorizontalScope()) { Variable v = cachedVariables[i]; if (GUIExtension.ButtonLabel(v.key, boldLabelStyle, variableLayoutOption)) { AssetDatabase.OpenAsset(template, v.line); GUIUtility.ExitGUI(); } v.value = EditorGUILayout.TextField(v.value, replaceLayoutOption); cachedVariables[i] = v; } } } GUILayout.FlexibleSpace(); newFileName = EditorGUILayout.TextField("File Name", newFileName); if (!string.IsNullOrEmpty(newFileName) && !newFileName.Contains(".")) { newFileName += defaultFileExtension; } string fullPath = cachedPath + newFileName; EditorGUILayout.TextField("File Path", fullPath); bool notEnoughArguments = template == null || cachedVariables == null || string.IsNullOrEmpty(newFileName) || EditorApplication.isCompiling; using (new EditorGUI.DisabledGroupScope(notEnoughArguments)) { if (GUILayout.Button("Save")) { string str = CodeGenerator.Generate(template, cachedVariables); CodeGenerator.SaveAs(str, fullPath); } } }