unity2019获取dll库中某个脚本的guid和localID,写一个右键菜单工具
时间: 2024-02-06 10:04:15 浏览: 133
好的,让我来解答你的问题。
要实现获取dll库中某个脚本的guid和localID,可以使用Unity Editor提供的AssetDatabase API。具体实现步骤如下:
1. 在Unity Editor中创建一个Editor脚本,并命名为“GetGUIDAndLocalID.cs”。
2. 在脚本中引用Unity Editor命名空间以及其他需要使用到的命名空间。
```csharp
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor.Callbacks;
```
3. 编写一个静态方法“GetSelectedScript()”,该方法获取选中的脚本文件。
```csharp
static MonoScript GetSelectedScript()
{
var selectedObj = Selection.activeObject;
var path = AssetDatabase.GetAssetPath(selectedObj);
if (string.IsNullOrEmpty(path))
return null;
var script = AssetDatabase.LoadAssetAtPath(path, typeof(MonoScript)) as MonoScript;
if (script == null || script.GetClass() == null)
return null;
return script;
}
```
4. 实现右键菜单功能,通过AssetDatabase生成GUID和localID,并使用EditorUtility.DisplayDialog()方法进行弹出提示框显示。
```csharp
[MenuItem("Assets/Get GUID and LocalID")]
static void GetGUIDAndLocalID()
{
var script = GetSelectedScript();
if (script == null)
return;
var assetPath = AssetDatabase.GetAssetPath(script.GetInstanceID());
var symbols = AssetDatabase.LoadAssetAtPath<MonoScript>(assetPath).GetClass().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(fieldInfo => fieldInfo.IsDefined(typeof(SerializeField), false)).Select(fieldInfo => fieldInfo.Name).ToList();
var component = Selection.activeGameObject.GetComponent(script.GetClass());
if (component == null)
return;
var serObj = new SerializedObject(component);
var propGUID = serObj.FindProperty("m_Script");
var GUID = propGUID.objectReferenceValue != null ? AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(propGUID.objectReferenceValue)) : "N/A";
var asset = (MonoScript)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(GUID), typeof(MonoScript));
if (asset == null)
return;
var localID = serObj.targetObject != null ? serObj.targetObject.GetInstanceID().ToString() : "";
var message = string.Format("GUID: {0}\nLocal ID: {1}\nSymbols List: {2}", GUID, localID, string.Join(",", symbols.ToArray()));
EditorUtility.DisplayDialog("GUID and LocalID", message, "OK");
}
```
5. 最后在Unity Editor中右键需要获取guid和localID的脚本文件,选择“Get GUID and LocalID”即可弹出显示该脚本文件的GUID和localID。
这就是一个简单的右键菜单工具,在Unity Editor中通过调用AssetDatabase API获取dll库中某个脚本的guid和localID。希望能对你有所帮助。
阅读全文