Android logcat как использовать unity

Лог файлы

Бывают случаи, когда вам требуется получить информацию из логов вашей webplayer сборки, вашего standalone проигрывателя, устройства, на котором вы запускали своё приложение или из редактора. Обычно вам требуется сперва найти эти логи, если у вас возникла проблема и вы хотите узнать что пошло не так.

На Mac логи webplayer’а, standalone проигрывателя и редактора можно получить с помощью стандартной утилиты Console.app .

На Windows логи webplayer’а и редактора находятся в скрытых папках, которые не видны по умолчанию в Проводнике Windows. См. ниже.

Редактор

Лог редактора можно открыть прямо в Unity с помощью меню Open Editor Log в окне Console.

/Library/Logs/Unity/Editor.log

Mac OS X
Windows XP C:\Documents and Settings\имяпользователя\Local Settings\Application Data_\Unity\Editor\Editor.log
Windows Vista/7 C:\Users\имяпользователя\AppData\Local\Unity\Editor\Editor.log

На Windows, файл лога редактора находится в локальной папке данных приложений (AppData): %LOCALAPPDATA%\Unity\Editor\Editor.log, где LOCALAPPDATA соответствует значению в CSIDL_LOCAL_APPDATA.

На Mac можно получить доступ ко всем логам с помощью стандартной утилиты Console.app .

Webplayer

/Library/Logs/Unity/WebPlayer.log and Player.log Windows XP C:\Documents and Settings\имяпользователя\Local Settings\Temp\UnityWebPlayer\log\log_UNIQUEID.txt Windows Vista/7 C:\Users\имяпользователя\AppData\Local\Temp\UnityWebPlayer\log\log_UNIQUEID.txt Windows Vista/7 + IE7 + UAC C:\Users\имяпользователя\AppData\Local\Temp\Low\UnityWebPlayer\log\log_UNIQUEID.txt

На Windows лог webplayer’а хранятся во временной папке: %TEMP%\UnityWebPlayer\log\log_UNIQUEID.txt, где TEMP соответствует значению GetTempPath.

Standalone проигрыватель

/Library/Logs/Unity/Player.log Windows __ | _EXECNAME_Data_\output_log.txt | |Linux__

/.config/unity3d/ИмяКомпании/ИмяПродукта/Player.log

На Windows, EXECNAME_Data — это папка рядом с исполняемым файлом игры.

Учтите, что у Windows и Linux standalone сборок расположение лог файла можно менять (или вообще отключать ведение лога). См. страницу о командной строке для дополнительной информации.

Лог устройства можно просматривать в XCode через GDB консоль или Organizer Console. Последнее полезно для получения логов “падения”, когда ваше приложение не было запущено через отладчик XCode.

The Troubleshooting and Bugreporting guides may be useful for you.

Android

Лог устройства можно просматривать через консоль logcat. Используйте приложение adb (которое находится в папке Android SDK/platform-tools directory ) с параметром logcat :

Другой способ изучения логов LogCat — использовать Dalvik Debug Monitor Server (DDMS). DDMS можно запустить либо из Eclipse , либо из папки Android SDK/tools . DDMS также предоставляет множество других инструментов для отладки.

Tizen

Лог устройства можно просматривать через sdb console. Используйте приложение sdb (которое находится в папке Tizen SDK/tools directory ) с параметром dlog в конце:

If you would like to only see messages from Unity you may add a filter. The filter specification is similar to that for Android. The following command will display only messages for the Unity log.

Windows Store

Windows Store Apps (On Desktop) __ | %userprofile%\AppData\Local\Packages

\TempState\UnityPlayer.log | |Windows Phone__ Can be retrieved with Windows Phone Power Tools, also check out this tool as well
Windows Phone IsoStoreSpy.

WebGL

On WebGL, log output is written to the browser’s JavaScript console.

Доступ к лог файлам в Windows

На Windows лог файлы находятся в папках, которые по умолчанию скрыты. В Windows XP вы можете включить видимость скрытых папок в Проводнике Windws с помощью Сервис->Свойства папки…->Вид (вкладка) .

На Windows Vista/7 вы можете сделать видимой папку AppData в Проводнике Windows с помощью Сервис->Свойства папки…->Вид (вкладка) . Меню Сервис по умолчанию скрыто, но может быть включено с помощью одиночного нажатия клавиши ALT.

Источник

Android Logcat Guide

Overview

Android Logcat Package is a utility for displaying log messages coming from Android device in Unity Editor. Read more about Android Logcat Document.

Requirements

  • Compatible with Unity 2019.1 or above.
  • Requires Unity’s Android support module.
  • Active platform in Unity has to be set to Android.

Supported features

  • Device connnection
    • Via USB
    • Via Wifi
  • Device selection
  • Package selection
  • Log
    • Copy
    • Save
    • Clear
    • Filter by
      • Priority
      • Tag
    • Search by
      • Text
      • Regex
  • Auto run
  • Screen capture
  • Stacktrace resolving

Installing Android Logcat

To install Android Logcat package, follow the instructions in the Package Manager documentation.

You can access Android Logcat window in Unity Editor via

  • Menu: Window > Analysis > Android Logcat
  • Shortcut: Alt+6 on Windows, Option+6 on macOS.

Using Android Logcat

The toolbar is on the top of the window. Most Android Logcat controls can be found here.

Device Connection

Connecting devices through USB and Wifi are both supported.

Connect via USB
The devices connected through USB will be added to the device list automatically when starting Android logcat window.

Connect via Wifi
Go to the devices list and click as below.

And a window to enter an ip address will be popped up as below.

Device Selection
The device list contains all the connnected devices, but you can only select one device at a time from the list.

Package Selection

The package selection list contains:

  • Package of the top activity which is currently running on the selected device.
  • Package from the player settings if it’s running on the selected device (Doesn’t have to be the the top running activity).

You can only select one package at a time, only the log messages come from the selected package will be shown in the logcat console window. Alternatively you can select No Filter, messages coming from all package will be shown.

Log Controls

The log window contains multiple predefined columns, you can enable/disable them by right clicking on the columns.

Copy
The selected logs can be copied to the clipboard. You can right click on the messages and select Copy.

Save
The selected logs can be saved to file. You can right click on the messages and select Save Selection.

Clear
You can clear all the logs by click the Clear button on the toolbar.

Search
You can input text in the text field on the toolbar to search logs by text. You can also toggle Regex on to treat contents in the text field as regex expression.

Filter

By Priority
You can right click on the Priority column to select or deselect priorities. Priorities are predefined according to the Android Logcat Document.

By Tag
Right click on the Tag column to select or deselect tags. You can also add or remove a tag by following steps:

  1. Find a message with the tag you want to add.
  2. Right click on the message and select Add Tag or Remove Tag.

Screen Capture

You can use Capture Screen button on the toolbar to capture a screenshot of the selected device. You can also Save the screenshot as file.

Auto Run

When Auto Run is toggled, Android Logcat window will be launched automatically if you do Build And Run in Build Settings window.

Stacktrace Resolving

One benefit of using Android Logcat package is automatic stacktrace resolving. The addr2line tool in Android NDK is used to convert the addresses in the crash logs to the file names and line numbers. Below is an example of what’s added to log.

The original log from Android logcat

The log shown in Android Logcat window in Unity Editor

To use this feature, you need to

  • Have Android NDK installed and set the NDK path in Unity (Menu: Editor >Preferences. >External Tools).
  • Have the corresponding symbol files installed with Unity.

Источник

Filtering Unity Logs With Logcat (Android)

Android application logs can be viewed with the adb logcat command. For more adb commands you can read this post. UnityEngine.Debug.Log(string message) writes message to the console with the stacktrace information that follows immediately after any custom message you specify. IMHO these extra stacktrace information is not needed — does not makes our lives easier while debuging unity games on an android device.

Debug logs should help find the bugs and tell everything important. Extra data added by UnityEngine to the logs makes the logs show twice less information and increases visual clutter. Removing noise from the logs and making important lines easily recognizable saves your precious time. This old post tells how we use syntax highlighting in Sublime Text editor to make our logs more eye-friendly.

Below is the screenshot of logcat output of a Unity3D game running on an android emulator (API level 23). Can you see the needless spam?

We should remove unnecessary information lines so we can focus on the lines that are more meaningful for us. Below python script reads the logcat output and filters out Unity Engine logs. So we can see our log messages more clearly.

Here is a screenshot of the same logcat output processed with the above script:

Warnings and errors are printed with a different color. This makes it very easy to see these lines among hundreds of lines. Exceptions are also marked with a different color. Script can be run with the following shell command on MAC and Linux platforms.

Try it and you’re welcome to add new features to the script.

Источник

Решение проблем при разработке под Android

Ошибка “No Platforms Found”:

  1. Удалите установленный Android SDK и убедитесь, что у вас нигде не установлены ещё копии.
  2. Обновите Java до последней стабильной версии. Никогда не забывайте, что хоть самая последняя версия не должна конфликтовать, у пользователей в прошлом всё равно бывали проблемы.
  3. Скачайте свежую копию самого последнего ADT Bundle и установите его следуя инструкциям. Это должно корректно откалибровать инструменты разработки: http://developer.android.com/sdk/index.html
  4. Настройте Unity на работу с установленным Android SDK.

Unity не удаётся установить ваше приложение на ваше устройство

  1. Убедитесь, что ваш компьютер видит ваше устройство и может взаимодействовать с ним. Для деталей см. Публикация сборок.
  2. Проверьте консоль Unity на наличие сообщений об ошибках. Это часто помогает в определении проблемы.

Если у вас появляется ошибка “Unable to install APK, protocol failure” во время сборки, то это значит, что ваше устройство подключено через USB-порт с низким питанием (возможно порт на клавиатуре или ещё на какой-нибудь периферии). Если такое случается, то попробуйте подсоединить устройство в USB порт на самом компьютере.

Ваше приложение падает сразу после запуска.

  1. Убедитесь, что вы не пытаетесь использовать NativeActivity с устройствами, которые это не поддерживают.
  2. Попробуйте убрать все нативные плагины, что у вас есть.
  3. Попробуйте отключить stripping.
  4. Используйте adb logcat чтобы получить отчёт о крахе с вашего устройства.

Building DEX Failed

Это ошибка, которая выдаёт сообщение, вроде следующего:-

Обычно это вызвано неверной версией Java на вашем компьютере. Обновление Java до последней версии обычно решает проблему.

Приложение падает через несколько секунд после начала проигрывания видео.

Убедитесь, что Settings->Developer Options->Don’t keep activities не включено на вашем телефоне. Проигрыватель видео — это отдельное приложение и поэтому обычное игровое приложение будет закрыто, если проигрыватель видео включён.

Моя игра закрывается, когда я жму кнопку сна

Измените тег activity в файле AndroidManifest.xml так , чтобы он содержал тег android:configChanges , сделайте это таким образом, как описано здесь.

Пример тега activity может выглядеть, например, вот так:-

Источник

Читайте также:  Что может смарт тв приставка андроид
Оцените статью