Unity复制选中脚本并修改器文件名与类名

时间:2022-02-12 19:14:59

虽然我们是程序员,但是无谓的编码应当能免则免,重复的工作会大大占用我们的时间。在一些情况下我们不得不需要创建许多类似的脚步,里面的结构相同,但是其功能却不一样,功能我们要自己写,但是结构等代码我们其实可以偷懒的。

 1 Unity复制选中脚本并且将其重命
 2 这个代码目的是为了应对创建重复性较大的脚本,使用后将创建新脚本时会在重命名时将脚本内部的类名修改
 3 
 4 脚本应当放在Editor
 5 ```
#if UNITY_EDITOR
6 using UnityEngine; 7 using System.Collections; 8 using UnityEditor.ProjectWindowCallback; 9 using System.IO; 10 using UnityEditor; 11 12 public class CopySelectScript 13 { 14 static string path = ""; 15 public static string oldFileName = ""; 16 [MenuItem("Assets/CopySelectScript", false, 0)]//Create/ 17 public static void CreateBmobTab() 18 { 19 var file = Selection.activeObject; 20 if (file!= null && file.GetType() != typeof(File)) 21 { 22 path = AssetDatabase.GetAssetPath(file); 23 oldFileName = file.name; 24 25 ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,ScriptableObject.CreateInstance<CopyScriptAssetAction>(), 26 GetSelectedPathOrFallback() + "/NewCloneScript.cs", 27 null, 28 path); 29 } 30 } 31 public static string GetSelectedPathOrFallback() 32 { 33 string path = "Assets"; 34 foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets)) 35 { 36 path = AssetDatabase.GetAssetPath(obj); 37 if (!string.IsNullOrEmpty(path) && File.Exists(path)) 38 { 39 path = Path.GetDirectoryName(path); 40 break; 41 } 42 } 43 return path; 44 } 45 } 46 47 class CopyScriptAssetAction : EndNameEditAction 48 { 49 public override void Action(int instanceId, string pathName, string resourceFile) 50 { 51 //创建资源 52 UnityEngine.Object obj = CreateAssetFromTemplate(pathName, resourceFile); 53 //高亮显示该资源 54 ProjectWindowUtil.ShowCreatedAsset(obj); 55 } 56 internal static UnityEngine.Object CreateAssetFromTemplate(string pahtName, string resourceFile) 57 { 58 //获取要创建的资源的绝对路径 59 string fullName = Path.GetFullPath(pahtName); 60 //读取本地模板文件 61 StreamReader reader = new StreamReader(resourceFile); 62 string content = reader.ReadToEnd(); 63 reader.Close(); 64 65 //获取资源的文件名 66 string fileName = Path.GetFileNameWithoutExtension(pahtName); 67 string oldFileName = Path.GetFileNameWithoutExtension(resourceFile); 68 //替换默认的文件名 69 //content = content.Replace("#TIME", System.DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss dddd")); 70 content = content.Replace(oldFileName, fileName); 71 72 //写入新文件 73 StreamWriter writer = new StreamWriter(fullName, false, System.Text.Encoding.UTF8); 74 writer.Write(content); 75 writer.Close(); 76 77 //刷新本地资源 78 AssetDatabase.ImportAsset(pahtName); 79 AssetDatabase.Refresh(); 80 81 return AssetDatabase.LoadAssetAtPath(pahtName, typeof(UnityEngine.Object)); 82 } 83 } 84 #endif 85 ```