Unity 6.3
0 онлайн 55 гостей 3 в системе
Вход
Введение в сетевое взаимодействие многопользовательских игр Глава 8 из 11 Оригинал, стр. 72

Тестирование и отладка сетевых игр

Русский

Тестирование и отладка сетевых игр

Тестирование и отладка многопользовательских игр отличаются от работы с однопользовательскими проектами. Учитывайте основные этапы рабочего процесса сетевого проекта:

- При локальном тестировании запускают несколько экземпляров игры и проверяют взаимодействие игроков. Для разработки приложения используйте сборки Player, пакет Multiplayer Play Mode и Network Scene Visualization. - Имитируйте сетевые условия с помощью скриптов или компонента NetcodeTransport. Так можно воспроизвести задержку, джиттер и потерю пакетов, характерные для реальных сетей.

- Управление клиентскими подключениями охватывает присоединение, повторное подключение и отключение клиентов. - Для журналирования и поиска причин неполадок используйте инструменты отладки. - Вспомогательный инструмент командной строки автоматизирует тестирование: запускает экземпляры игры с заданными ролями и сетевыми условиями.

Локальное тестирование Локальное тестирование - важная часть разработки многопользовательской игры: несколько экземпляров приложения имитируют взаимодействие разных игроков в сетевых условиях.

Сборки Player Запуская несколько экземпляров исполняемого файла игры, можно создавать сеансы и присоединяться к ним. Экземпляры также можно запускать одновременно с Unity Editor, чтобы на одном устройстве имитировать хоста и подключающихся игроков.

Multiplayer Play Mode (MPPM) Входящий в Unity 6 пакет Multiplayer Play Mode (MPPM) позволяет имитировать до четырех игроков на одном компьютере разработчика, используя одни и те же исходные ресурсы. Отдельные сборки Player не требуются, поэтому тестовые итерации занимают меньше времени.

Пользователям macOS В macOS для запуска нескольких экземпляров приложения нужна командная строка. Выполните в Terminal команду open, чтобы запустить отдельный экземпляр приложения.

Например, команда open -n YourAppName.app в Terminal запускает отдельный экземпляр приложения YourAppName.

Имитация сетевых условий При локальном тестировании все экземпляры игры используют один сетевой интерфейс. Задержка между клиентами практически отсутствует, поэтому для имитации реальной среды ее необходимо добавить искусственно. Задержка, джиттер и потеря пакетов влияют на игровой процесс. Проверка приложения в неблагоприятных сетевых условиях помогает убедиться, что итоговая сборка будет надежно работать через интернет.

Набор тестовых условий зависит от целевой платформы, региона и особенностей игры. Для начала используйте задержку около 100-150 мс на настольных системах и 200-300 мс на мобильных устройствах, а также потерю 5-10% пакетов. Обязательно проверяйте джиттер и потерю пакетов: они воспроизводят реальную нестабильность сети. Дополнительные рекомендации приведены на этой странице документации.

Для локального тестирования в редакторе можно совместно использовать Network Simulator из пакета Multiplayer Tools и Multiplayer Play Mode. Для тестирования отладочных сборок рекомендуем добавлять неблагоприятные сетевые условия с помощью Network Simulator и собственного кода: окно Network Simulator работает только в редакторе. Для тестирования релизных сборок в Windows рекомендуем clumsy, а в macOS и iOS Network Link Conditioner. В macOS скриптуемой альтернативой Network Link Conditioner служит dummynet: этот гибко настраиваемый инструмент входит в состав операционной системы.

Подробности см. в разделе «Системные инструменты эмуляции сетевых условий».

Тестирование клиентских подключений Тестирование управления клиентскими подключениями помогает избежать ошибок и обеспечить плавный игровой процесс. Проверьте следующие сценарии:

Подключение клиентов: - Присоединение к новому сеансу, повторное подключение после выхода или завершения хостинга, позднее присоединение к уже идущей игре и обработка отклоненного подключения.

- Влияет ли предыдущее состояние клиента на подключение и правильно ли сервер реплицирует состояние игры. - Корректно ли сервер обрабатывает повторное и позднее подключение.

Отключение клиентов: - Штатное завершение работы клиента, тайм-ауты и последствия потери соединения с хостом или сервером. - Правильно ли сбрасываются неуничтоженные объекты, связанные с сеансом, и может ли клиент подключиться к новой игре.

Запуск сеанса хостом или сервером: - Запуск нового сеанса после завершения предыдущего, особенно в играх с клиентским хостингом. - Влияет ли состояние приложения перед новым сеансом на игру.

Завершение работы хоста или сервера: - Штатное завершение работы хоста или сервера, особенно при использовании внешних сервисов, например Unity Gaming Services или Lobby. - Оповещаются ли о завершении работы клиенты и внешние сервисы. Тщательная проверка этих сценариев помогает обеспечить стабильную и комфортную сетевую игру. Подробнее см. в материале «Тестирование управления клиентскими подключениями». .

Приемы отладки многопользовательских игр При отладке многопользовательских игр действуют все общие принципы разработки игр. Однако для некоторых типичных сетевых сценариев нужны специальные приемы и подходы. Ниже - приемы, полезные при разработке многопользовательских игр в Unity: - Отладочная графика: линии Debug.DrawRay и Debug.DrawLine помогают показывать сетевые позиции, предполагаемые направления движения и взаимодействия объектов. Они особенно полезны при параллельном просмотре записей игрового процесса нескольких участников.

- Line Renderer с поддержкой Netcode: визуальная обратная связь может показывать направление, значение или другую полезную для проекта отладочную метрику. Реализация приведена в примере скрипта Line Renderer с поддержкой Netcode.

- Текстовые журналы: позволяют отслеживать невизуальные события, например RPC, и сопутствующие сведения. Добавляйте к сообщениям сетевой тик и идентификатор клиента, чтобы по журналам было проще восстановить хронологию.

- Эмуляция сетевых условий: Network Simulator имитирует на уровне приложения искусственную задержку, джиттер и потерю пакетов, помогая находить связанные с ними ошибки. Подробнее см. в разделе «Системные инструменты эмуляции сетевых условий». - Запись экрана: одновременно записывайте экземпляры клиента и сервера для сравнения игрового процесса в реальном времени. В отладочной сборке отмечайте каждый кадр идентификатором клиента и номером кадра - это дает ориентир при параллельном просмотре. - Увеличение фиксированного временного шага: даже с качественной отладочной графикой и журналами бывает трудно понять происходящее при покадровом анализе. Увеличение значения Fixed Timestep, например до 0,2, делает поведение игры в каждом кадре нагляднее. - Точки останова: при долгой паузе в отладчике сетевое соединение может завершиться по тайм-ауту. Временно увеличьте тайм-аут, чтобы избежать отключения во время остановки игры. Дополнительные советы приведены в руководстве «Приемы и хитрости отладки многопользовательских игр».

Вспомогательный инструмент командной строки Постоянный запуск и тестирование многопользовательских сборок из Unity Editor занимает много времени. Инструмент командной строки может автоматизировать запуск и проверку сборок вне редактора. Начать можно с примера скрипта NetworkCommandLine. Добавьте компонент NetworkCommandLine к GameObject, чтобы скрипт вошел в сборку и был доступен через командную строку. В окне Player Settings откройте Settings for PC, Mac & Linux Standalone > Resolution and Presentation и установите для Resolution значение Windowed. Так несколько экземпляров игры будет удобнее тестировать рядом друг с другом. Скрипт NetworkCommandLine должен сначала проверить, что игра запущена вне редактора. Затем он считывает аргументы командной строки, определяет нужный режим (server, host или client) и запускает соответствующие службы. Это позволяет задавать сетевую роль сборки при запуске из командной строки.

Создайте сборку через File > Build Settings и протестируйте её из командной строки. В Windows: Откройте командную строку и перейдите в каталог со сборкой. Запускайте экземпляры сервера и клиента отдельными командами, при необходимости изменив путь. Например:

<Путь к проекту>\HelloWorld.exe -mode server <Путь к проекту>\HelloWorld.exe -mode client В macOS: Откройте Terminal и используйте аналогичные команды, указав пути в формате macOS. Например: <Путь к проекту>∕HelloWorld.app∕Contents∕MacOS∕<Имя проекта> -mode server <Путь к проекту>∕HelloWorld.app∕Contents∕MacOS∕<Имя проекта> -mode client При необходимости направьте вывод экземпляров игры в текстовые файлы с помощью флага -logfile: так его удобнее отслеживать и анализировать.

English

Testing and debugging networked games

Testing and debugging your multiplayer games works differently than their single-player counterparts. Be aware of the general workflow for your netcode projects: —

Local testing runs multiple instances of the game to assess the interaction between players. Use player builds, the Multiplayer Play Mode package, and Network Scene Visualization to develop your application.

Simulate network conditions with scripts or the NetcodeTransport component. This can recreate latency, jitter, and packet loss to mimic real-world network issues.

Client-connection management handles behaviors for joining, reconnecting, and disconnecting clients.

Logging uses the debug tools to monitor troubleshoot issues.

A command line helper launches game instances with specific roles and network conditions to automate testing.

Local testing Developing multiplayer games relies on local testing, where you simulate multiple instances of the game to mimic how different players interact in networked conditions.

Player builds Player builds allow for hosting and joining games by running multiple instances of the game executable. You can also run these alongside the Unity Editor, enabling simultaneous hosting and joining of games on a single device to simulate multiplayer scenarios.

Multiplayer Play Mode (MPPM) Included in Unity 6, the Multiplayer Play Mode (MPPM) package enables the simulation of up to four players on a single development device using the same source assets. This feature eliminates the need for separate player builds, reducing build times during testing.

macOS users For macOS users, running multiple instances of an app requires command line commands. Use the open command at the terminal to launch a separate instance of your application. For example, at the Terminal, execute open -n YourAppName.app to launch a separate instance of the YourAppName application.

Simulating network conditions When testing locally, all game instances run on the same network interface. There will be little to no latency between the clients, so you’ll need to introduce artificial conditions to simulate a real-world environment. Latency, jitter, and packet loss can impact gameplay. Testing your application with less than ideal network conditions can ensure that your final build performs well over the internet. Determining which conditions to test depends on factors such as target platform, region, and the design of your game. As a starting point, use latency values around 100-150 ms for desktop and 200-300 ms for mobile, along with 5-10% packet loss. Testing with jitter and packet loss is essential, as it introduces realistic instability. See this documentation page for more guidelines. For testing locally within the Editor, you can use the Network Simulator tool from the Multiplayer Tools along with Multiplayer Play Mode. For testing development builds, we suggest using the Network Simulator tools with some custom code to inject adverse network conditions into the build (the Network Simulator window only works in the Editor). For testing release builds, we suggest using clumsy if you’re on Windows and Network Link Conditioner if you’re on macOS or iOS. A scriptable alternative to Network Link Conditioner on macOS is dummynet, which offers great control and comes packaged with the operating system. See System-wide network conditioners for full details.

Testing client connections Testing client connection management in a networked game is important to avoid bugs and provide a smooth gaming experience. Here are some things to test and watch out for:

Clients connecting: —

Test cases can include clients joining new game sessions, rejoining after leaving or hosting, late-joining ongoing games, and handling denied connections.

Consider if the client’s previous state affects connection and if the game state replicates correctly from the server.

Check if the server handles reconnections or late-joining properly.

Clients disconnecting: —

Test graceful client shutdowns, timeouts, and the impact of losing connection to the host/server.

Ensure objects tied to the game session reset properly if not destroyed, and that clients can reconnect to a new game.

Host/Server starting the session: —

Test starting new game sessions and after shutting down previous sessions, especially in client-hosted games.

Consider if the application’s state before starting a new session affects the game.

Host/Server shutting down: —

Test graceful shutdowns of the host/server, especially when using external services like Unity Game Services or lobby services.

Ensure clients are notified of the shutdown, and external services are properly informed.

Thorough attention to these test cases can help maintain a stable and enjoyable networked gaming experience. For more specifics, see Testing Client Connection Management.

Techniques for debugging multiplayer games When debugging multiplayer games, all conventional game development wisdom applies. However, certain scenarios that are typical to multiplayer game development call for special tricks and approaches. Below is a list of techniques that may help you when developing multiplayer games with Unity: —

Debug drawing techniques: Use debug lines from Debug.DrawRay and Debug.DrawLine to indicate network positions, movement intentions, and objection interactions. They are useful when combined with side-by-side recordings of multiplayer gameplay.

Netcode-enabled Line Renderer: Sometimes it’s useful to have visual feedback that shows a specific direction, value, or any other useful debug metric pertinent to your project. See this example script for implementing a Netcode-enabled Line Renderer.

Text-Based logging: Text-based logging can track non-visual events (such as RPCs) and information. Include network tick and client id in log messages to make it easier to build a timeline when reading the logs.

Network conditioning: Use the Network Simulator tools for application-level network conditioning. This can simulate artificial network conditions and help test for errors specific for latency, jitter, and packet loss. Read more at System-wide network conditioners.

Screen recordings: Record both client and server instances simultaneously to compare real-time gameplay. In debug builds, be sure to stamp each frame with the client ID and the current frame number; this provides a visual reference for a side-by-side comparison.

Increasing fixed timestep: Despite using good debug rendering and logging, it can be hard sometimes to understand what’s going on – even when going through the frames one by one. Increasing the FixedTimeStep setting to a large value (for example, 0.2) can provide extra clarity into the game’s behavior during each frame.

Using Breakpoints: When using breakpoints to debug a game, your connection may time out if you stay too long in this mode. Since it pauses your game, you can temporarily increase the timeout value to avoid disconnecting.

See this guide on Techniques and tricks for debugging multiplayer games for more tips and techniques.

Command line helper Repeatedly launching and testing multiplayer builds from within the Unity Editor can be timeconsuming. Consider using a command-line tool to automate launching and testing multiplayer game builds outside of the Editor environment. This sample NetworkCommandLine script can help you get started. Attach the NetworkCommandLine component to a GameObject to ensure that the script is included in your build and can be accessed via the command line. In the Player Settings, beneath Settings for PC, Mac, & Linux Standalone, select Resolution and Presentation. Set the Resolution to Windowed. This will make it easier to test multiple instances of your game side by side. The NetworkCommandLine script should first check if the game is running outside the Editor. If so, it should read the command-line arguments to determine the desired mode (server, host, or client) and start the corresponding services. This will allow you to launch your game build with specific network roles from the command line. Build a binary from File > Build Settings then test at the command line. On Windows: Open the Command Prompt and navigate to the directory where you saved your build. Use specific commands to start the server or client instances of your game, adjusting the paths as necessary. For example: <Path to Project>\HelloWorld.exe -mode server <Path to Project>\HelloWorld.exe -mode client On macOS: On macOS, open the Terminal and use similar commands as mentioned above, but adjust the paths to match the macOS directory structure. For example: <Path to Project>/HelloWorld.app/Contents/MacOS/<Project Name> -mode server <Path to Project>/HelloWorld.app/Contents/MacOS/<Project Name> -mode client Optionally, you can log the output of your game instances to text files for easier tracking and analysis with the -logfile flag.