控制Unity中脚本的运行顺序
生活随笔
收集整理的這篇文章主要介紹了
控制Unity中脚本的运行顺序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路就是先拿到腳本和腳本掛的特性值 然后使用monoImportor.Set修改執行順序
using System; using System.Collections.Generic; #if UNITY_EDITOR using System.IO; using UnityEditor; #endif using UnityEngine;[AttributeUsage( AttributeTargets.Class, Inherited = false, AllowMultiple = false )] sealed class ExecutionOrderAttribute : Attribute {public readonly int ExecutionOrder = 0;public ExecutionOrderAttribute( int executionOrder ) {ExecutionOrder = executionOrder;}#if UNITY_EDITORprivate const string PB_TITLE = "Updating Execution Order";private const string PB_MESSAGE = "Hold on to your butt, Cap'n!";private const string ERR_MESSAGE = "Unable to locate and set execution order for {0}";//這個特性類似 InitializeLoad 點擊運行的時候會加載腳本 或者你在vs修改了什么東西 也會加載一次[InitializeOnLoadMethod]private static void Execute() {//用類型拿到這個程序集中所有的腳本 Type type = typeof( ExecutionOrderAttribute );//我糙 真是服了 用var居然不用引用命名空間var assembly = type.Assembly;//可以嘗試進行打印查看程序及中的類集合 Type[] types = assembly.GetTypes();var scripts = new Dictionary<MonoScript, ExecutionOrderAttribute>();var progress = 0f;var step = 1f / types.Length;foreach ( var item in types ) {//拿到類身上的特性var attributes = item.GetCustomAttributes( type, false );//如果腳本上的特性大于一個跳過繼續if ( attributes.Length != 1 )continue;var attribute = attributes[0] as ExecutionOrderAttribute;var asset = "";//從Asset中拿到這個腳本的唯一標識符(就是哪個guid特性里面的值)var guids = AssetDatabase.FindAssets( string.Format( "{0} t:script", item.Name ) );if ( guids.Length > 1 ) {foreach ( var guid in guids ) {var assetPath = AssetDatabase.GUIDToAssetPath( guid );var filename = Path.GetFileNameWithoutExtension( assetPath );if ( filename == item.Name ) {asset = guid;break;}}} else if ( guids.Length == 1 ) {asset = guids[0];} else {Debug.LogErrorFormat( ERR_MESSAGE, item.Name );return;}//將guid碼轉化為資源路徑然后加載對應的腳本MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( asset ) );//將腳本和對應的特性加載到集合中scripts.Add( script, attribute );}bool changed = false;foreach ( var item in scripts ) {//查看七樓八樓的對應解釋//https://forum.unity.com/threads/script-execution-order-manipulation.130805/if ( MonoImporter.GetExecutionOrder( item.Key ) != item.Value.ExecutionOrder ) {changed = true;break;}}if ( changed ) {foreach ( var item in scripts ) {var cancelled = EditorUtility.DisplayCancelableProgressBar( PB_TITLE, PB_MESSAGE, progress );progress += step;if ( MonoImporter.GetExecutionOrder( item.Key ) != item.Value.ExecutionOrder ) {MonoImporter.SetExecutionOrder( item.Key, item.Value.ExecutionOrder );}if ( cancelled ) break;}}Debug.Log("排序行為執行");EditorUtility.ClearProgressBar();} #endif }
轉載于:https://www.cnblogs.com/chenggg/p/10781462.html
總結
以上是生活随笔為你收集整理的控制Unity中脚本的运行顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Echarts中国地图的显示
- 下一篇: 销售漏斗