链接LabelField

 

public class TestWindow : EditorWindow
{
    
    [MenuItem("Window/TestWindow")]
    static void ShowWindow()
    {
        var window = GetWindow<TestWindow>();
        window.titleContent = new GUIContent("TestWindow");
        window.Show();
    }
    
    private void OnGUI()
    {
        AssetLabelField("SampleScene","Assets/Scenes/SampleScene.unity");
        UrlLabelField("www.baidu.com","https://www.baidu.com");
    }
    
    public static void AssetLabelField(string label, string assetPath, params GUILayoutOption[] options)
    {
        var position = LinkLabelField_internal(new GUIContent(label), options);
        if (GUI.Button(position, label, LinkStyle))
        {
            var asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
            Selection.activeObject = asset;
            EditorGUIUtility.PingObject(asset);
        }
    }

    public static void UrlLabelField(string label, string url, params GUILayoutOption[] options)
    {
        var uiRect = LinkLabelField_internal(new GUIContent(label), options);
        if (GUI.Button(uiRect, label, LinkStyle))
        {
            Application.OpenURL(url);
        }
    }
    
    private static Rect LinkLabelField_internal(GUIContent label, params GUILayoutOption[] options)
    {
        var uiRect = GUILayoutUtility.GetRect(label, LinkStyle, options);
        
        Handles.BeginGUI();
        Handles.color = LinkStyle.normal.textColor;
        Handles.DrawLine(new Vector3(uiRect.xMin, uiRect.yMax), new Vector3(uiRect.xMax, uiRect.yMax));
        Handles.color = Color.white;
        Handles.EndGUI();
        
        EditorGUIUtility.AddCursorRect(uiRect, MouseCursor.Link);
        
        return uiRect;
    }
    
    private static GUIStyle _linkStyle = null;
    private static GUIStyle LinkStyle
    {
        get
        {
            if (_linkStyle == null)
            {
                _linkStyle = new GUIStyle(EditorStyles.label);
                _linkStyle.wordWrap = false;
                _linkStyle.fontSize = 12;
                _linkStyle.normal.textColor = new Color(0x00 / 255f, 0x78 / 255f, 0xDA / 255f, 1f);
                _linkStyle.hover.textColor = Color.yellow;
                _linkStyle.stretchWidth = false;
            }

            return _linkStyle;
        }
    }

}

 

【参考】

Unity编辑器拓展之三十六:LinkFileLabelField和LinkUrlLabelField | JingFengJi

 

posted @ 2022-04-25 23:41  yanghui01  阅读(37)  评论(0编辑  收藏  举报