Unity debug android app

Attaching MonoDevelop Debugger To An Android Device

You can attach the MonoDevelop debugger to an Android device with ADB via TCP/IP. The process is described below.

Enable “USB debugging” on your device and connect the device to your development machine via USB cable. Ensure your device is on the same subnet mask and gateway as your development machine. Also, make sure there are no other active network connections on the device, i.e. disable data access over mobile/cellular network.

On your development machine, open up your terminal/cmd and navigate to the location of the ADB. You can find the ADB tool in /platform-tools/

Restart host ADB in TCP/IP mode with the following command:

This will have enabled ADB over TCP/IP using port 5555. If port 5555 is unavailable, you should use a different port (see ADB.) The following output should be produced:

  • Find out the IP address of your Android device (Settings ->About ->Status) and input the following command:

DEVICEIPADDRESS is the actual IP address of your Android device. This should produce the following output:

  • Ensure that your device is recognised by inputting the following command:

This should produce the following output:

Build and run your Unity application to the device. Ensure you build your application with Development Build flag enabled and Script Debugging turned on.

Disconnect the USB cable as the device no longer needs to be connected to your development machine.

Finally, while the application is running on your device, open your script in MonoDevelop, add a breakpoint, select “Run” -> “Attach to Process” and select your device from the list. (It might take a few seconds for the device to appear in the list. It may not appear in the list if the application is not running or if the device’s display goes to sleep).

For some more details and for troubleshooting, see the Wireless Usage section in the Android developers guide for the ADB.

Note: The device sends multicast messages and the editor and MonoDevelop subscribe/listen for them. For the process to work, your network will need to be setup correctly for Multicasting.

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright © 2017 Unity Technologies. Publication: 5.6-001N. Built: 2017-07-12.

Источник

Real-time дебаг Android и iOS приложений на Unity

Когда разработка проекта идёт на компьютере, проблемы просмотра лога не встаёт. Но когда начинаешь разрабатывать на планшете, то всё становится гораздо печальнее. Разработчики движка добавили много разных полезных вещей в профайлер, но к сожалению забыли о простой консоли, чтобы переключившись на её вкладку разработчик мог смотреть сообщения от своей игры и отправлять какие-то консольные команды прямо с компьютера на планшет.
Это упущение мы сейчас и будем исправлять.

Если кратко, мы создадим таблицу в Google Docs, и скрипт, который будет при вызове добавлять туда значение. И создадим скрипт в движке, который будет слушать команды типа Debug.Log() и отправлять их нашему скрипту. Дел на 10 минут, но удобство повышается значительно. Если у вас в проекте реализована консоль, то можно сделать чтобы скрипт отправлял отклик (скажем содержимое написанного вами в какой-то ячейке таблицы), можно это передавать в качестве команды в консоль.
Работает всё довольно быстро, у меня интернет 50 mbit, сообщения появляются практически мгновенно. Таблица Google обновляется сама, рефрешить не надо.

Читайте также:  Пульт ду для android tv box x96 x 96

Сначала простейший вариант, для понимания сути.

1. Настройка серверной части.

Для серверной части нужен аккаунт Google, потому что создавать таблицу мы будем в Google Drive.

В меню создайте скрипт (Tools -> Script Editor -> Script as Web App).

Удалите созданный темплейт и скопируйте следующий код:

. В коде id 0Ap2rwVyty8rZdElOTFhlTG9BSEZGY29BZDlpQWdMR2c надо заменить на id вашей страницы, его можно взять из URL созданного вами Spreadsheet.

При вызове этого скрипта он будет брать созданную вами таблицу, и добавлять в последнюю строку время и значение, которое пришло по запросу GET с ключом p.

Сохраните скрипт под именем, к примеру, RemoteLogger.

Теперь надо создать версию (File -> Manage versions -> Save new version).

Теперь мы можем опубликовать его (Publish -> Deploy as Web App) с такими настройками:
. Execute the app as: me
. Who has access to the app: Anyone, even anonymous

После нажатия Deploy Google даёт нам URL такого вида:
script.google.com/macros/s/AKfycbyubkC0TQbyrRYvVD9nYezvxuDkya0Asbvff67EUK0G0oqFndws/exec
при его запуске в созданной вами таблице появится строка со временем запуска и значением undefined, если в конце дописать ?p=test
script.google.com/macros/s/AKfycbyubkC0TQbyrRYvVD9nYezvxuDkya0Asbvff67EUK0G0oqFndws/exec?p=test
то в таблице появится строка со словом «test»

Можно считать, что серверная часть работает нормально.

2. Клиентский Unity-скрипт.

Создайте скрипт, к примеру RemoteLogger.cs и поместите туда следующий код:

. Не забудьте поменять значение url на адрес вашего скрипта.

Этот скрипт слушает лог, берёт сообщение, кодирует для передачи по методу GET и отсылает его нашему скрипту, чтобы он добавил его в таблицу.

После добавления к GameObject и запуска, на открытой в вашем браузере таблице должно появиться «Hello world!» (таблица обновляется автоматически). Если этого не произошло, то вероятно вы забыли поменять id таблицы, url или при публикации скрипта настроили права неправильно.

3. Батчинг.
Если в программе много сообщений, то слишком расточительно создавать для каждого новый запрос. Мы будем передавать до 10 сообщений зараз, в зависимости от того, сколько есть на данный момент.
Сложного в изменениях ничего нет, поэтому я просто опубликую код и поясню кратко.

Сначала исправляем скрипт на сервере:

То есть перебираются параметры от p0 до p9, если есть значение — то оно добавляется.

Теперь код класса RemoteLogger.cs

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

В зависимости от ваших нужд, можно передавать в таблицу что это за сообщение error/warning/message и подсвечивать его соответсвенно, как это сделано в Unity.
Можно передавать стек, если вам важно видеть, откуда было оно отправлено.
Теоретически можно использовать построение графиков.
Можно сделать обратную связь, и передвать какие-то команды в игру, там уже слушая отклик скрипта и передавая его в консоль. Добавляется легко.
Можно консоль не делать, а добавить пункты меню, к примеру «Make screenshot», «Enable cheats», и отправлять их.

В общем, есть возможности для доработки и расширения. Делитесь вашими идеями и их реализациями, возможно они кому-нибудь пригодятся. 🙂

Читайте также:  Iap cracker для андроида

PS: Большое спасибо автору этой статьи из песочницы.

Источник

The Hardest Work

How to Debug a Unity APK on an Android device with Visual Studio

Oh my goodness this was far too difficult… so I had to write it up! This guide assumes you have some experience with Unity, debugging in Visual Studio, and building APK’s (let me know if you don’t in the comments!).

If you’re using Unity, you’re coding in C#, and you’re using Visual Studio… Here’s how you can setup a remote debugger to debug your APK on an Android device.

I’m currently using the following tools but the steps are generally the same:

Unity v2020.1.7f1

Visual Studio Community 2019

Android Studio v3.5 & SDK

Samsung Galaxy S9

Step 1: When you build your APK you’ll want to tick 2 boxes on the build settings menu. ‘Development Build‘ & ‘Script Debugging

Step 2: Create your build as usual and copy the build to your Android device. Connect your Android Device to your PC via USB. Be sure your machine and Android device are connected to the same wifi network.

Step 3: If you haven’t previously, Enable USB Debugging on your Android Device.

  1. Open Settings
  2. Select System
  3. Scroll to the bottom and select About Phone
  4. Scroll to the bottom and tap ‘Build Number’ 7 times
  5. Return to the previous screen and find ‘Developer Options’ near the bottom
  6. Scroll down and select to enable ‘USB Debugging’

Step 4: Back on your computer, open up a cmd prompt (or terminal) as an administrator and change your directory to:

Step 5: Back on your Android Device, find the Android Device’s IP by going to:

  1. Go to Settings
  2. Go to ‘About Phone’
  3. Got to ‘Status’
  4. Find ‘IP Address’
  5. Write it down…

Step 6: Back in your command prompt enter the following command:

Step 7: Connect to your Device with this command using your IP from Step 5:

Step 8: Open Visual Studio from within Unity and go to the ‘Debug’ menu option. Select ‘Attach Unity Debugger’

Step 9: You should see a small menu popup and it should display both your computer and your connected Android device. Select your Android device, set some break points in your code, and have fun!

Hopefully this guide saves you some time and headache on trying to figure this out. If you need more information on connecting your device that this guide doesn’t provide let me know so I can update it!

Источник

Android symbols

To help you debug your application, Unity can generate a package that contains symbol files for native Unity libraries. Symbol files contain a table that translates active memory addresses into information you can use, like a method name. The translation process is called symbolication. You can upload a symbols package to the Google Play Console to see a human-readable stack trace on the Android Vitals dashboard.

There are two types of symbol files:

  • Public: A small file that contains a symbol table. For more information, see Public symbols.
  • Debug: Contains everything that a public symbol file contains, and full debugging information that you can use for more in-depth debugging. For more information, see Debugging symbols.
Читайте также:  Android sdk local line

You can generate symbol files for the following libraries:

  • libmain : Responsible for initial Unity engine loading logic.
  • libunity : Unity’s engine code.
  • libil2cpp : Contains C# scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
    See in Glossary from the project converted to C++ code.

Unity generates the libmain and libunity symbol files. Gradle An Android build system that automates several build processes. This automation means that many common build errors are less likely to occur. More info
See in Glossary generates the libil2cpp symbol file.

Public symbols

A public symbol file contains information that resolves function addresses to human-readable strings. Unity uses the —strip-debug parameter to create public symbols that remove more in-depth debug information. This makes public symbol files and packages smaller than debugging symbol files and packages.

Debugging symbols

A debugging symbol file contains full debugging information and a symbol table. Use it to:

  • Resolve stack traces and to debug applications that you have source code available for.
  • Attach a native debugger to the application and debug the code.

Unity uses the —only-keep-debug parameter to create debugging symbols. For more information, see –only-keep-debug in the Linux user manual.

Note: If debugging symbols aren’t available, Unity places a public symbol file in your project at build time. For the libmain and libunity libraries, debugging symbols are not available and Unity always generates public symbol files.

Generating a symbols package

There are two ways to enable symbols package generation for your application:

  • In the Build Settings window:
  • Open the Build Settings window (menu: File >Build Settings).
  • Select the Android platform.
  • Set Create symbols.zip to one of the following:
    • Public
    • Debugging
  • Use the EditorUserBuildSettings.androidCreateSymbols API.

After you enable symbols package generation, building your project generates a .zip file that contains symbol files for the libmain and libunity library. If you set your scripting backend A framework that powers scripting in Unity. Unity supports three different scripting backends depending on target platform: Mono, .NET and IL2CPP. Universal Windows Platform, however, supports only two: .NET and IL2CPP. More info
See in Glossary to IL2CPP A Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. More info
See in Glossary
, the .zip also contains a symbol file for the libil2cpp library. Unity places this symbols package within the output directory.

If you enable Export Project in the Android Build Settings, Unity doesn’t build the project. Instead, it exports the project for Android Studio, generates symbols for libmain and libunity , and places them within unityLibrary/symbols// in the output directory. When you build your exported project from Android Studio, Gradle generates the libil2cpp symbol file and places it within the unityLibrary/symbols// directory alongside the libmain and libunity symbol file.

Using symbols in the Google Play console

After you upload your application to Google Play, you can upload a public symbols package for it. For information on how to do this, see Google’s documentation: Deobfuscate or symbolicate crash stack traces.

Note: Google Play doesn’t symbolicate crashes that your application received before you uploaded the symbols package.

Источник

Оцените статью