Version: 2018.2
Características actualmente no soportadas por Unity iOS.
Reportando bugs de falla en iOS

Troubleshooting en dispositivos iOS

Hay algunas situaciones con iOS donde su juego puede funcionar perfectamente en el Editor de Unity pero no funciona o, ni siquiera comienza en el dispositivo actual. Los problemas a menudos están relacionados al código o la calidad de contenido. Esta sección describe los escenarios más comunes.

El juego para de responder después de un poco. Xcode muestra “interrupted” en la barra de estado.

Hay un número de razones de por qué esto puede suceder. Las causas típicas incluyen:

  1. Errores de Scripting como el uso de variables no inicializadas, etc.
  2. Utilizar librerías de nativas compiladas de terceros. Tales librerías activa un problema conocido en el linker del SDK de iOS y puede causar problemas(crashes) aleatorios.
  3. Using generic types with value types as parameters (e.g. List<int>, List<SomeStruct>, List<SomeEnum>) for serializable script properties.
  4. Utilizar reflexión cuando managed code stripping esté activado.
  5. Errores en la intefaz de plugin nativa (el método para manejar código signature no concuerda con la función de código nativo signature). La información de la consola de depuración Xcode puede a veces ayudar a detectar estos problemas (Menú de Xcode: View > Debug Area > Activate Console).

La consola de Xcode muestra "Program received signal: “SIGBUS” o EXC_BAD_ACCESS error.

This message typically appears on iOS devices when your application receives a NullReferenceException. There are two ways to figure out where the fault happened:

Administrar los seguimientos de pila (Managed Stack Traces)

Unity includes software-based handling of the NullReferenceException. The AOT compiler includes quick checks for null references each time a method or variable is accessed on an object. This feature affects script performance, which is why it is enabled only for development builds (enable the script debugging option in build settings dialog). If everything was done right and the fault actually is occurring in .NET code then you won’t see EXC_BAD_ACCESS anymore. Instead, the .NET exception text will be printed in the Xcode console (or else your code will just handle it in a “catch” statement). Typical output might be:

Unhandled Exception: System.NullReferenceException: A null value was found where an object instance was required.
  at DayController+$handleTimeOfDay$121+$.MoveNext () [0x0035a] in DayController.js:122 

This indicates that the fault happened in the handleTimeOfDay method of the DayController class, which works as a coroutine. Also, if it is script code then you will generally be told the exact line number (e.g. “DayController.js:122”). The offending line might be something like the following:

 Instantiate(_imgwww.assetBundle.mainAsset);

Esto puede suceder si, digamos, el script accede un asset bundle sin primero revisar que fuera descargado correctamente.

Seguimientos de pila nativos (Native stack traces)

Native stack traces are a much more powerful tool for fault investigation but using them requires some expertise. Also, you generally can’t continue after these native (hardware memory access) faults happen. To get a native stack trace, type bt all into the Xcode Debugger Console. Carefully inspect the printed stack traces; they may contain hints about where the error occurred. You might see something like:

...
Thread 1 (thread 11523): 

1. 0 0x006267d0 in m_OptionsMenu_Start ()
1. 1 0x002e4160 in wrapper_runtime_invoke_object_runtime_invoke_void__this___object_intptr_intptr_intptr ()
1. 2 0x00a1dd64 in mono_jit_runtime_invoke (method=0x18b63bc, obj=0x5d10cb0, params=0x0, exc=0x2fffdd34) at /Users/mantasp/work/unity/unity-mono/External/Mono/mono/mono/mini/mini.c:4487
1. 3 0x0088481c in MonoBehaviour::InvokeMethodOrCoroutineChecked ()
...

Firstly, you should find the stack trace for “Thread 1”, which is the main thread. The very first lines of the stack trace will point to the place where the error occurred. In this example, the trace indicates that the NullReferenceException happened inside the OptionsMenu script’s Start method. Looking carefully at this method implementation would reveal the cause of the problem. Typically, NullReferenceExceptions happen inside the Start method when incorrect assumptions are made about initialization order. In some cases only a partial stack trace is seen on the Debugger Console:

Thread 1 (thread 11523): 

1. 0 0x0062564c in start ()

Esto indica que los símbolos nativos fueron stripped durante la construcción final de la aplicación. El seguimiento de pila completo puede ser obtenido con los siguiente procedimientos:

  • Quite la aplicación del dispositivo.
  • Limpie todos los objetivos (targets)
  • Construya y corra.
  • Obtenga los seguimiento de pila nuevamente como es descrito arriba.

EXC_BAD_ACCESS comienza ocurriendo cuando una librería externa está vinculada a la aplicación de Unity iOS.

This usually happens when an external library is compiled with the ARM Thumb instruction set. Currently, such libraries are not compatible with Unity. The problem can be solved easily by recompiling the library without Thumb instructions. You can do this for the library’s Xcode project with the following steps:

  • In Xcode, select View > Navigators > Show Project Navigator from the menu
  • Select the Unity-iPhone project, activate Build Settings tab
  • In the search field enter: Other C Flags
  • Add -mno-thumb flag there and rebuild the library.

Si la fuente de la librería no está disponible, usted debería preguntarle al proveedor por una versión sin-thumb de la librería.

La consola de Xcode muestra “WARNING -> applicationDidReceiveMemoryWarning()” y la aplicación cae inmediatamente después

Sometimes, you might see a message like Program received signal: “0”. This warning message is often not fatal and merely indicates that iOS is low on memory and is asking applications to free up some memory. Typically, background processes like Mail will free some memory and your application can continue to run. However, if your application continues to use memory or ask for more, the OS will eventually start killing applications and yours could be one of them. Apple does not document what memory usage is safe, but empirical observations show that applications using less than 50% of all device RAM do not have major memory usage problems. The main metric you should rely on is how much RAM your application uses. Your application memory usage consists of three major components:

  • Application code (the OS needs to load and keep your application code in RAM, but some of it might be discarded if really needed)
  • Native heap (used by the engine to store its state, your assets, etc. in RAM)
  • Managed heap (used by your Mono runtime to keep C# objects)
  • GLES driver memory pools: textures, framebuffers, compiled shaders, etc. Your application memory usage can be tracked by two Xcode Instruments tools: Activity Monitor and Allocations. You can start from the Xcode Run menu: Product > Profile and then select specific tool or via Xcode > Open Developer Tools > Instruments. Activity Monitor tool shows all process statistics including Real memory which can be regarded as the total amount of RAM used by your application. Note: OS and device HW version combination might noticeably affect memory usage numbers, so you should be careful when comparing numbers obtained on different devices.

** Nota:** El internal profiler muestra sólo el heap asignado por los scripts de .NET. El uso total de memoria se puede determinar a través de las herramientas de Xcode como se muestra arriba. Esta figura incluye partes del binario de la aplicación, algunos búferes de marco estándar, búferes de estado interno del motor Unity, el heap de ejecución .NET (número impreso por el internal profiler), el heap de controladores GLES y algunas otras cosas misceláneas.

The other tool displays all allocations made by your application and includes both native heap and managed heap statistics. The important statistic is the Net bytes value.

Para mantener el uso de memoria bajo:

  • Reduzca el tamaño binario de la aplicación utilizando las opciones de stripping de iOS más fuertes y evite dependencias innecesarias en diferentes bibliotecas .NET. Consulte las páginas de manual de player settings y player size optimization para obtener más detalles.
  • Reduzca el tamaño de su contenido. Utilice la compresión de PVRTC para texturas y utilice modelos de bajo peso. Consulte la página del manual acerca de reducir el tamaño del archivo para obtener más información.
  • Don’t allocate more memory than necessary in your scripts. Track mono heap size and usage with the internal profiler.

Consultar el sistema operativo acerca de la cantidad de memoria libre puede parecer una buena idea para evaluar qué tan bien está ejecutándose su aplicación. Sin embargo, la estadística de memoria libre es probable que no sea fiable ya que el sistema operativo utiliza una gran cantidad de búferes dinámicos y cachés. El único enfoque fiable es realizar un seguimiento del consumo de memoria para su aplicación y utilizarlo como la métrica principal. Preste atención a cómo las gráficas de las herramientas descritas anteriormente cambian con el tiempo, especialmente después de cargar nuevos niveles.

El juego se ejecuta correctamente cuando se inicia desde Xcode pero se bloquea al cargar el primer nivel cuando se inicia manualmente en el dispositivo.

There could be several reasons for this. You need to inspect the device logs to get more details. Connect the device to your Mac, launch Xcode and select Window > Devices and Simulators from the menu. Select your device in the window’s left toolbar, then click on the Show the device console button and review the latest messages carefully. Additionally, you may need to investigate crash reports. You can find out how to obtain crash reports here: http://developer.apple.com/iphone/library/technotes/tn2008/tn2151.html.

La consola del organizador de Xcode contiene el mensaje “killed by SpringBoard”.

Hay un límite de tiempo mal documentado para una aplicación de iOS para renderizar sus primeros frames y procesar input. Si su aplicación excede este límite, SpringBoard lo matará. Esto puede ocurrir en una aplicación con una primera escena demasiado grande, por ejemplo. Para evitar este problema, es aconsejable crear una pequeña escena inicial que sólo muestra una pantalla de bienvenida, espera un frame o dos con yield y luego comenzar a cargar la escena real. Esto se puede hacer con un código tan sencillo como el siguiente:

IEnumerator Start() {
    yield return new WaitForEndOfFrame();
// Do not forget using UnityEngine.SceneManagement directive
    SceneManager.LoadScene("Test");
}

Type.GetProperty() or Type.GetValue() cause crashes on the device

Actualmente Type.GetProperty() y Type.GetValue() están soportados sólo para el perfil .NET 2.0 Subset. Puede seleccionar el nivel de compatibilidad de .NET API en el Player Settings.

Nota: Type.GetProperty() y Type.GetValue() podrían ser incompatibles con la eliminación de código administrado y puede que tenga que ser excluido (puede proporcionar una lista de tipos no desplegables personalizada durante el proceso de eliminación para lograr esto). Para obtener más detalles, consulte la guía iOS player size optimization.

El juego falla con el mensaje de error “ExecutionEngineException: Attempting to JIT compile method ‘SometType`1<SomeValueType>:.ctor ()’ while running with –aot-only.”

The Mono .NET implementation for iOS is based on AOT (ahead of time compilation to native code) technology, which has its limitations. It compiles only those generic type methods (where a value type is used as a generic parameter) which are explicitly used by other code. When such methods are used only via reflection or from native code (i.e. the serialization system) then they get skipped during AOT compilation. The AOT compiler can be hinted to include code by adding a dummy method somewhere in the script code. This can refer to the missing methods and so get them compiled ahead of time.

void _unusedMethod() {
    var tmp = new SomeType<SomeValueType>();
}

Note: Value types are basic types, enums and structs.

Se producen varias fallas en el dispositivo cuando se usa una combinación de System.Security.Cryptography y stripping de código administrado

Los servicios de .NET Cryptography dependen en gran medida de la reflexión y, por lo tanto, no son compatibles con el descifrado de código administrado, ya que esto implica el análisis de código estático. A veces, la solución más fácil para los bloqueos es excluir todo el namespace System.Security.Crypography del proceso de stripping.

The stripping process can be customized by adding a custom link.xml file to the Assets folder of your Unity project. This specifies which types and namespaces should be excluded from stripping. Further details can be found in the iOS player size optimization guide.

link.xml

<linker>
       <assembly fullname="mscorlib">
               <namespace fullname="System.Security.Cryptography" preserve="all"/>
       </assembly>
</linker>

La aplicación falla cuando se utiliza System.Security.Cryptography.MD5 con stripping de código manejado

You should consider the above advice or try working around this problem by adding extra references to specific classes to your script code:

object obj = new MD5CryptoServiceProvider();

“Ran out of trampolines of type 0/1/2” runtime error

This error usually happens if you use lots of recursive generics. You can hint to the AOT compiler to allocate more trampolines of type 0, type 1 or type 2. Additional AOT compiler command line options can be specified in the Other Settings section of the Player settings. For for type 0 trampolines specify ntrampolines=ABCD, where ABCD is the number of new trampolines required (i.e. 4096). For type 1 trampolines specify nrgctx-trampolines=ABCD and for type 2 trampolines specify nimt-trampolines=ABCD.

After upgrading Xcode Unity iOS, runtime fails with message “You are using Unity iPhone Basic. You are not allowed to remove the Unity splash screen from your game”

With some latest Xcode releases there were changes introduced in PNG compression and optimization tool. These changes might cause false positives in Unity iOS runtime checks for splash screen modifications. If you encounter such problems try upgrading Unity to the latest publicly available version. If this does not help, you might consider the following workaround:

  • Reemplace su proyecto de Xcode desde cero cuando construya desde Unity (en lugar de anexarlo)
  • Delete already installed projects from device
  • Clean project in Xcode (Product > Clean)
  • Clear Xcode’s Derived Data folders (Xcode > Preferences > Locations)

Si esto todavía no ayuda intente inhabilitar la re-compresión del png en Xcode:

  • Abra su proyecto de Xcode
  • Select Unity-iPhone project
  • Select Build Settings tab
  • Look for Compress PNG files option and set to NO

Las descargas de WWW funcionan bien en el Unity Editor y en Android, pero no en iOS

The most common mistake is to assume that WWW downloads are always happening on a separate thread. On some platforms this might be true, but you should not take it for granted. Best way to track WWW status is either to use the yield statement or check status in Update method. You should not use busy while loops for that.

El error “PlayerLoop called recursively!” ocurre cuando se utiliza Cocoa mediante un llamado de función nativo desde un script

Some operations with the UI will result in iOS redrawing the window immediately (the most common example is adding a UIView with a UIViewController to the main UIWindow). If you call a native function from a script, it will happen inside Unity’s PlayerLoop, resulting in PlayerLoop being called recursively. In such cases, you should consider using the performSelectorOnMainThread method with waitUntilDone set to false. It will inform iOS to schedule the operation to run between Unity’s PlayerLoop calls.

El Profiler o Depurador incapaz de ver el juego corriendo en el dispositivo iOS

  • Check that you have built a Development build, and checked the Script Debugging and Autoconnect Profiler boxes (as appropriate).
  • La aplicación que se ejecuta en el dispositivo hará una difusión multicast a 225.0.0.222 en el puerto UDP 54997. Compruebe que la configuración de red permite este tráfico. A continuación, el profiler realizará una conexión al dispositivo remoto en un puerto del rango 55000 - 55511 para obtener datos del profiler del dispositivo. Estos puertos necesitarán estar abiertos para el acceso UDP.

DLLs faltantes

If your application runs ok in editor but you get errors in your iOS project this may be caused by missing DLLs (e.g. I18N.dll, I19N.West.dll). In this case, try copying those dlls from within the Unity.app to your project’s Assets\Plugins folder. The location of the DLLs within the unity app is: Unity.app\Contents\Frameworks\Mono\lib\mono\unity You should then also check the stripping level of your project to ensure the classes in the DLLs aren’t being removed when the build is optimised. Refer to the iOS Optimisation Page for more information on iOS Stripping Levels.

Informes de la consola del depurador de Xcode: ExecutionEngineException: intentar el método de compilación JIT ‘(wrapper nativo a administrado) Test: TestFunc (int)’ mientras se ejecuta con –aot-only

Typically, such a message is received when the managed function delegate is passed to the native function, but the required wrapper code wasn’t generated when the application was built. You can help AOT compiler by hinting which methods will be passed as delegates to the native code. This can be done by adding the MonoPInvokeCallbackAttribute custom attribute. Currently, only static methods can be passed as delegates to the native code.

Código ejemplo:

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
using AOT;

public class NewBehaviourScript : MonoBehaviour {
    [DllImport ("__Internal")]
    private static extern void DoSomething (NoParamDelegate del1, StringParamDelegate del2);

    delegate void NoParamDelegate ();
    delegate void StringParamDelegate (string str);
    
    [MonoPInvokeCallback(typeof(NoParamDelegate))]
    public static void NoParamCallback() {
        Debug.Log ("Hello from NoParamCallback");
    }
    
    [MonoPInvokeCallback(typeof(StringParamDelegate))]
    public static void StringParamCallback(string str) {
        Debug.Log(string.Format("Hello from StringParamCallback {0}", str));
    }

    // Use this for initialization
    void Start() {
        DoSomething(NoParamCallback, StringParamCallback);
    }
}

Xcode lanza error de compilación: “ld : unable to insert branch island. No insertion point available. for architecture armv7”, “clang: error: linker command failed with exit code 1 (use -v to see invocation)”

This error usually means there is just too much code in single module. Typically, it is caused by having lots of script code or having big external .NET assemblies included into build. And enabling script debugging might make things worse, because it adds quite few additional instructions to each function, so it is easier to hit that limit.

Enabling managed code stripping in player settings might help with this problem, especially if big external .NET assemblies are involved. But if the issue persists then the best solution is to split user script code into multiple assemblies. The easiest way to this is move some code to Plugins folder. Code at this location is put to a different assembly. Also, check the information about how special folder names affect script compilation.


Características actualmente no soportadas por Unity iOS.
Reportando bugs de falla en iOS