Unity 框架

CreateScriptFromTemplate.cs 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.IO;
  4. using UnityEditor.ProjectWindowCallback;
  5. using System.Text;
  6. using System;
  7. namespace TFramework
  8. {
  9. public class CreateScriptFromTemplate
  10. {
  11. public static void Create(Type type, string templatePath, string destName, Texture2D icon)
  12. {
  13. ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
  14. 0,
  15. ScriptableObject.CreateInstance(type) as EndNameEditAction,
  16. destName,
  17. icon,
  18. templatePath
  19. );
  20. }
  21. public static void Create<T>(string templatePath, string destName, Texture2D icon) where T : DoCreateScriptAsset
  22. {
  23. ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
  24. 0,
  25. ScriptableObject.CreateInstance<T>(),
  26. destName,
  27. icon,
  28. templatePath
  29. );
  30. }
  31. }
  32. public abstract class DoCreateScriptAsset : EndNameEditAction
  33. {
  34. public virtual string Suffix { get; set; } = ".cs";
  35. public override void Action(int instanceId, string pathName, string resourceFile)
  36. {
  37. UnityEngine.Object obj = CreateAssetFromTemplate(pathName, resourceFile);
  38. ProjectWindowUtil.ShowCreatedAsset(obj);
  39. }
  40. internal UnityEngine.Object CreateAssetFromTemplate(string pathName, string resourceFile)
  41. {
  42. string className = pathName.Remove(0, pathName.LastIndexOf('/') + 1);
  43. pathName += Suffix;
  44. string fullName = Path.GetFullPath(pathName);
  45. StreamReader reader = new StreamReader(resourceFile);
  46. string content = reader.ReadToEnd();
  47. reader.Close();
  48. content = ReplaceTemplateContent(className, content);
  49. StreamWriter writer = new StreamWriter(fullName, false, UTF8Encoding.UTF8);
  50. writer.Write(content);
  51. writer.Close();
  52. AssetDatabase.ImportAsset(pathName);
  53. AssetDatabase.Refresh();
  54. return AssetDatabase.LoadMainAssetAtPath(pathName);
  55. }
  56. /// <summary>
  57. /// 替换模版内容
  58. /// </summary>
  59. /// <param name="templateContent">替换内容</param>
  60. /// <returns></returns>
  61. public abstract string ReplaceTemplateContent(string className, string templateContent);
  62. }
  63. }