Networking.PlayerConnection.PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown

Unity · Версия 2020.3 LTS · Scripting · PlayerConnectionGUILayout

Networking.PlayerConnection.PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown

Объявление

public static void ConnectionTargetSelectionDropdown(Networking.PlayerConnection.IConnectionState state, GUIStyle style);

Параметры

state Состояние соединения, которое использует EditorWindow, отображающий раскрывающийся список. Используйте PlayerConnectionGUIUtility.GetConnectionState, чтобы получить состояние в OnEnable. Убедитесь, что вы избавились от этого состояния в OnDisable, чтобы избежать его утечки..
style Define the GUIStyle the drop-down button should be drawn in. A default drop-down button will be drawn if non is specified.

Описание

Отобразить раскрывающуюся кнопку и меню, чтобы пользователь мог выбрать и установить соединение с проигрывателем.

Это тот же элемент управления, который используется на панелях инструментов окна Profiler, FrameDebugger или окно Console. В раскрывающемся списке будут перечислены все доступные игроки и редакторы, к которым ваш редактор может подключиться и которые доступны для обнаружения. Он также предлагает вход для прямого подключения к IP-адресу.

Вам необходимо указать состояние подключения для вашего EditorWindow. Чтобы получить состояние, используйте PlayerConnectionGUIUtility.GetConnectionState в OnEnable. Убедитесь, что вы удалили состояние в OnDisable для EditorWindow, в котором вы его используете, чтобы избежать его утечки.

В настоящее время этот класс работает только для подключения, используемого инструментами профилирования и консолью. В будущем выпуске это будет работать с PlayerConnection.

using UnityEngine;
using UnityEngine.Profiling;
using UnityEditor;
using UnityEngine.Networking.PlayerConnection;
using UnityEditor.Networking.PlayerConnection;

public class MyWindow : EditorWindow
{
    // The state can survive for the life time of the EditorWindow so it's best to store it here and just renew/dispose of it in OnEnable and OnDisable, rather than fetching repeatedly it in OnGUI.
    IConnectionState attachProfilerState;

    [MenuItem("Window/My Window")]
    static void Init()
    {
        MyWindow window = (MyWindow)GetWindow(typeof(MyWindow));
        window.Show();
    }

    private void OnEnable()
    {
        // The state of the connection is not getting serialized and needs to be disposed of.
        // Therefore, it's recommended to fetch it in OnEnable and call Dispose() on it in OnDisable.
        attachProfilerState = PlayerConnectionGUIUtility.GetConnectionState(this, OnConnected);
    }

    private void OnConnected(string player)
    {
        Debug.Log(string.Format("MyWindow connected to {0}", player));
    }

    private void OnGUI()
    {
        // Draw a toolbar across the top of the window and draw the drop-down in the toolbar drop-down style too
        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
        PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown(attachProfilerState, EditorStyles.toolbarDropDown);

        switch (attachProfilerState.connectedToTarget)
        {
            case ConnectionTarget.None:
                //This case can never happen within the Editor, since the Editor will always fall back onto a connection to itself.
                break;
            case ConnectionTarget.Player:
                Profiler.enabled = GUILayout.Toggle(Profiler.enabled, string.Format("Profile the attached Player ({0})", attachProfilerState.connectionName), EditorStyles.toolbarButton);
                break;
            case ConnectionTarget.Editor:
                // The name of the Editor or the PlayMode Player would be "Editor" so adding the connectionName here would not add anything.
                Profiler.enabled = GUILayout.Toggle(Profiler.enabled, "Profile the Player in the Editor", EditorStyles.toolbarButton);
                break;
            default:
                break;
        }
        EditorGUILayout.EndHorizontal();
    }

    private void OnDisable()
    {
        // Не забывайте всегда избавляться от состояния!
        attachProfilerState.Dispose();
    }
}

Также см. раздел PlayerConnectionGUI.ConnectionTargetSelectionDropdown для ручного позиционирования, а также PlayerConnectionGUIUtility.GettionState и IConnectionState для получения сведений об обработке состояния для этого элемента управления пользовательского интерфейса.

Обновлено 17 ноября 2026 г.