Unity復制選中腳本並修改器文件名與類名
阿新 • • 發佈:2018-01-14
utf8 占用 edi 目的 time pro sts efi gets
雖然我們是程序員,但是無謂的編碼應當能免則免,重復的工作會大大占用我們的時間。在一些情況下我們不得不需要創建許多類似的腳步,裏面的結構相同,但是其功能卻不一樣,功能我們要自己寫,但是結構等代碼我們其實可以偷懶的。
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 ```
Unity復制選中腳本並修改器文件名與類名