生成预制体自动生成对应名称脚本并自动挂载
- B站视频教程
- 监听指定文件夹预制体变动
- 脚本生成
- 脚本自动挂载
- 完成源码和案例
B站视频教程
Unity Editor扩展 生成脚本并自动挂载到对应生成的预制体上
监听指定文件夹预制体变动
public class CustomAssetPostprocessor : AssetPostprocessor
{//所有的资源的导入,删除,移动,都会调用此方法,注意,这个方法是static的public static void OnPostprocessAllAssets( string[] importedAsset, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths ){//List<string> formList = new List<string>();//string history = Path.Combine( Application.persistentDataPath, "GenerateUIFormHistory.cachedat" );//if ( File.Exists( history ) )//{// string genHistory = File.ReadAllText( history );// string[] forms = genHistory.Split( ';' );// formList = new List<string>( forms );//}List<string> movedAssetsList = new List<string>( movedAssets );foreach ( string url in importedAsset ){if ( url.StartsWith( "Assets/BundleRes/UI/Form" ) && url.EndsWith( ".prefab" ) && !movedAssetsList.Contains( url ) ){//if ( !formList.Contains( str ) )//{// NewFormPrefabProc( str );//}
#if UNITY_2020_1_OR_NEWERstring form = Path.GetFileNameWithoutExtension( url );if ( !Directory.Exists( $"Assets/Scripts/UIForms/{form}" ) )
#endif{NewFormPrefab( url );}}}foreach ( string url in deletedAssets ){if ( url.StartsWith( "Assets/BundleRes/UI/Form" ) && url.EndsWith( ".prefab" ) && !movedAssetsList.Contains( url ) ){//Log.PINK( $"Check uIForm prefab deleted: {url}" );var formName = Path.GetFileNameWithoutExtension( url );var dependScriptFolder = $"Assets/Scripts/UIForms/{formName}";if ( Directory.Exists( dependScriptFolder ) ){Directory.Delete( dependScriptFolder, true );File.Delete( dependScriptFolder + ".meta" );//Log.PINK( $"Delete depend ScriptFolder: {dependScriptFolder}\nDelete depend scripts: {formName}.cs,{formName}Manager.cs" );}}}}
}
脚本生成
private static void NewFormPrefab( string assetPath ){if ( string.IsNullOrWhiteSpace( assetPath ) || string.IsNullOrEmpty( assetPath ) ){Log.Error( $"NewFormPrefabProc 传入路径为空或者空格: {assetPath}" );return;}var pathclips = assetPath.Split( '/' );var fileName = pathclips[ pathclips.Length - 1 ].Split( '.' )[ 0 ];string file = fileName + "";if ( !fileName.EndsWith( "Form" ) ){if ( fileName.EndsWith( "form" ) ){file = fileName.Replace( "form", "Form" );}else{file = fileName + "Form";}}//try//{// //newForm path// var newPath = assetPath.Replace( fileName, file );// //记录一下新创建的 避免循环导入// List<string> formList = new List<string>();// string history = Path.Combine( Application.persistentDataPath, "GenerateUIFormHistory.cachedat" );// string genHistory = string.Empty;// if ( File.Exists( history ) )// {// genHistory = File.ReadAllText( history );// string[] forms = genHistory.Split( ';' );// formList = new List<string>( forms );// }// if ( !formList.Contains( newPath ) )// {// if ( File.Exists( newPath ) )// {// File.Delete( newPath );// }// File.Copy( assetPath, newPath );// File.Delete( assetPath );// genHistory += $";{newPath}";// File.WriteAllText( Path.Combine( Application.persistentDataPath, "GenerateUIFormHistory.cachedat" ), genHistory );// }// else// {// return;// }//}//catch ( System.Exception e )//{// Debug.LogError( e );//}//预制体操作//var instance = PrefabUtility.LoadPrefabContents( assetPath );//instance.name = file;//PrefabUtility.SaveAsPrefabAsset( instance, "Assets/BundleRes/UI/Form/aaa2.prefab" );//PrefabUtility.UnloadPrefabContents( instance );var formClsName = file + "";var managerClsName = $"{file}Manager";var outputFolder = $"Assets/Scripts/UIForms/{file}/";if ( !Directory.Exists( outputFolder ) ){Directory.CreateDirectory( outputFolder );}EditorUtility.DisplayProgressBar( "Generate UIForm Derived ClassScript", $"class {managerClsName}", 0.3f );GenCSharpScript.GenScriptFromTemplate( "Assets/Frameworks/Editor/UIScriptTemplate/XXXFormManager.cs", outputFolder, managerClsName, ( ref string textContentProcessing ) =>{textContentProcessing = textContentProcessing.Replace( "XXXFormManager", managerClsName );textContentProcessing = textContentProcessing.Replace( "XXXForm", formClsName );} );EditorUtility.DisplayProgressBar( "Generate UIForm Derived ClassScript", $"class {formClsName}", 0.667f );GenCSharpScript.GenScriptFromTemplate( "Assets/Frameworks/Editor/UIScriptTemplate/XXXForm.cs", outputFolder, formClsName, ( ref string textContentProcessing ) =>{textContentProcessing = textContentProcessing.Replace( "XXXFormManager", managerClsName );textContentProcessing = textContentProcessing.Replace( "XXXForm", formClsName );} );EditorUtility.ClearProgressBar( );string error = AssetDatabase.RenameAsset( assetPath, file );if ( !string.IsNullOrEmpty( error ) ){Debug.LogError( error );return;}var newPath = assetPath.Replace( fileName, file );EditorPrefs.SetString( generateClassName, formClsName );EditorPrefs.SetString( generatePrefabPath, newPath );AssetDatabase.SaveAssets( );AssetDatabase.Refresh( );}
脚本自动挂载
public static string generateNamespaceName = "";public static string generateClassName = "generateClassName";public static string generatePrefabPath = "generatePrefabPath";[UnityEditor.Callbacks.DidReloadScripts]private static void OnScriptUpdateLoaded( ){string className = EditorPrefs.GetString( generateClassName );if ( string.IsNullOrEmpty( className ) ){return;}EditorUtility.DisplayProgressBar( "Mount scripts", $"{className} install...", 0f );var assemblies = AppDomain.CurrentDomain.GetAssemblies( );var defaultAssembly = assemblies.First( assembly => assembly.GetName( ).Name == "Assembly-CSharp" );var typeName = string.IsNullOrEmpty( generateNamespaceName ) ? className : generateNamespaceName + "." + className;var type = defaultAssembly.GetType( typeName );if ( type == null ){Debug.Log( "编译失败" );EditorUtility.ClearProgressBar( );return;}string prefabPath = EditorPrefs.GetString( generatePrefabPath );//为开发者提供额外处理接口try{GameObject prefabInstance = PrefabUtility.LoadPrefabContents( prefabPath );EditorUtility.DisplayProgressBar( "Mount scripts", $"{className} install...", 0.618f );var scriptComponent = prefabInstance.GetComponent( type );if ( !scriptComponent ){scriptComponent = prefabInstance.AddComponent( type );}AdditionalConfigurationForNewForm( prefabInstance );EditorUtility.DisplayProgressBar( "Mount scripts", $"{className} install...", 1f );PrefabUtility.SaveAsPrefabAssetAndConnect( prefabInstance, prefabPath, InteractionMode.AutomatedAction );}catch ( Exception e ){Debug.LogError( e );}AssetDatabase.Refresh( );EditorUtility.ClearProgressBar( );EditorPrefs.DeleteKey( generateClassName );}
完成源码和案例
项目源码: https://pan.baidu.com/s/1MqND3pPnxErDem9_1WJ-Rw?pwd=gjse 提取码: gjse