Titanium & Unity3D for iOS: Notes on Flurry Analytics – Parameters Take a Week to Show Up in Reports

I used an open source Flurry module developed by SoftGravity. It was easy to implement and seems to be working well. One potentially confusing thing with Flurry’s dashboard is that it’s not immediately clear how long it takes data to populate the various charts & reports.

“You currently have no event parameters to track.”

For example, I can see my parameter Name / Value pairs Event Logs. The little pie chart icon for Event Parameters shows up next to my events that have parameters. However, when I try to look at any of the reports for parameters that show up in the Event Logs I constantly get this message with no additional details: “You currently have no event parameters to track.” None of the FAQ pages on flurry.com mention this situation.

After installing the module, I’m calling logEvent, after initiating flurry w/ my API KEY, like so:

//in app.js: 
var flurry = require('sg.flurry');
	flurry.secureTransport(true); //use https to send request to make them more safe
	flurry.logUncaughtExceptions(true); //logs exception in objective-c code
	flurry.startSession('YOUR_API_KEY_HERE'); 
...

//in a content .js file:
flurry.logEvent( "My Footer Event" , {myfooter_link: 'Contact Us'} ); 

48 hrs after I created my application in the Flurry admin dashboard, this problem still persisted. At the time I was using Titanium SDK 2.1.3.GA and Titanium Studio, build: 2.1.2.201208301612.

Give it at least a week

5 days after I created the app in Flurry’s dashboard and started posting data to the Event Logs, my Event Parameters finally started showing up in the reports and the “You currently have no event parameters to track” message went away.

I first tried Flurry a while back with a test Unity3D project, using Prime31’s great Flurry for iOS plugin. It seemed to work well, but at the time, I didn’t pay much attention to the Event Parameters and how long they take to show up in the reports. Looking at my old Unity test data in Flurry’s dashboard, they’re certainly there now.

Unity3D for iOS: Relative Positioning with UIToolkit

Here’s one way to horizontally center a UIToolkit object, such as a UIButton, using positionCenterX(). Should work pretty good on the various iPad sizes, iPhone 4, iPhone 5. The one thing to keep in mind is the scale of the actual graphic will need to be adjusted, either via UIToolkit’s UI.cs class that listens for HD, SD or supper HD screen sizes or manually via your own code.

Javascript version

#pragma strict
public var buttonToolkit:UIToolkit;
private var newGameBtn:UIButton;

function Start() {
    newGameBtn = UIButton.create( buttonToolkit, "playBtnOff.png", "playBtnOn.png", 0, 0 );	
	newGameBtn.zIndex = 0;

	//centers it horizontally on iPad and iPhone: 
	newGameBtn.positionCenterX();
	//relatively positions it along y axis; slightly differnt actual position on iPads, iPhone 4, iPhone 5 
	newGameBtn.position.y = UIRelative.yPercentFrom( UIyAnchor.Bottom, 1.25f );	

	newGameBtn.highlightedTouchOffsets = new UIEdgeOffsets( 10 );	
	newGameBtn.onTouchUpInside += newGameBtnHandler;	
	newGameBtn.alphaFrom( 1.0f, 0.0f, Easing.Quintic.easeOut );
}

function newGameBtnHandler( sender:UIButton ) 
{
	Debug.Log("newGameBtn clicked!");
}

C# version

using UnityEngine;
using System;
using Prime31;

public class ExampleManagerScript : MonoBehaviour {

	//set via Inspector panel
	public UIToolkit buttonToolkit; 

    private UIButton newGameBtn;

	void Start() {	

		newGameBtn = UIButton.create( buttonToolkit, "playBtnOff.png", "playBtnOn.png", 0, 0 );	
		newGameBtn.zIndex = 0;

		//centers it horizontally on iPad and iPhone: 
		newGameBtn.positionCenterX();
		//relatively positions it along y axis; slightly differnt actual position on iPads, iPhone 4, iPhone 5 
		newGameBtn.position.y = UIRelative.yPercentFrom( UIyAnchor.Bottom, 1.25f );	

		newGameBtn.highlightedTouchOffsets = new UIEdgeOffsets( 10 );	
		newGameBtn.onTouchUpInside += newGameBtnHandler;	
		newGameBtn.alphaFrom( 1.0f, 0.0f, Easing.Quintic.easeOut );
	}

	void newGameBtnHandler( UIButton sender ) 
	{
		Debug.Log("newGameBtn clicked!");
	}
}

Unity3D for iOS: “The Executable was signed with invalid entitlements” message from Xcode (Xcode install) and “Failed to Install” from device (iTunes install)

When to install via iTunes, Device says this after almost finishing install progress bar when installing with Dev Provisioning Profile:

"Failed to Install" 

When tried via Xcode’s Organizer, get this message:

The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile. (0xE8008016).

Looks like Code Signing issue when I tried moving .p12 files to another machine and publishing from that other machine.

When I looked in KeyChain Access on my main machine, under “Keys” in the left side Category menu, the MyCompanyPrivateKeyName had “iPhone Developer: SoAndSo ($*@#&&#$)” certificate. BUT on my 2nd machine, the one I tried moving the .p12 files to, MyCompanyPrivateKeyName listed the “iPhone Distribution: Company Name” certificate. I had to delete the Certificates and Private Keys in KeyChain Access and then re-install them, making sure I install the Dev .p12 file first.

This didn’t fix the problem, however.

After some more poking around, I noticed that, since I had more than one developer certificate installed on that machine (my personal one and 2 company ones), Xcode was by default picking up the wrong Dev Provisioning Certificate and trying to incorrectly use it to code sign my .ipa. To fix this, in Xcode I had to

  • select the project name in the Navigator (left side bar in Xcode)
  • select Unity-iPhone under Project or Targets
  • select the Build Settings tab
  • find the Code Signing section & make sure the “iPhone Developer” profile specified there is correct and matches your app’s Bundle Identifier (com.yourCompany.YourAppName, unless you’re using a generic one via the “*” wildcard)

Unity3D for iOS: Black Screen After Loading Screen on iPad 3, iOS 6

I’ve heard of this error happening when you accidentally have a sprite sheet set to about 2048 pixels in width or height.

This just started happening to me, after I upgraded my Mac OS from 10.6.8 to 10.7.5, running Unity 3.5.6f4 and upgraded to TexturePacker Pro 3.0.1.

The error didn’t show for me on iPhone 4S or iPad 2. As soon as I tried to load my dev .ipa onto an iPad 3 running iOS 6 via iTunes, I started seeing the black screen.

Then I opened Xcode and hit Run with my iPad 3 plugged in and here’s the error that came up in Xcode’s Console:

- Completed reload, in  0.212 seconds
-> applicationDidBecomeActive()
UI texture is being autoloaded and it doesn't exist. Cannot find texturePackerConfigName: imgSheet4x

(Filename: /Applications/buildAgent/work/14194e8ce88cdf47/Runtime/ExportGenerated/iPhonePlayer-armv7/UnityEngineDebug.cpp Line: 43)

(lldb) 

Saw this in Thread 1 too:

My_App_Name`UISpriteManager_loadTextureAndPrepareForUse + 260 at Assembly-CSharp-firstpass.dll.s:17293: <<<<<< Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

Now, I’m not using any 4x sprite sheets in this particular project due to file size constraints.

I just had my production machine upgraded from OS X 10.6.8 to OS X 10.7.5. Looks like this is what did it. 10.6 couldn’t really detect iPad3’s high res display, so stuff published out of Unity3D on 10.6 just auto scaled everything and used the 2x sprite sheet. Now that I’m on OS X 10.7, the OS suddenly allows iPad3 detection, UIToolkit responds by trying to load the 4x texture, which I don’t have due to .ipa file size constraints.

Changing the following in UI.cs:

	isHD = true;
				scaleFactor = 4; 
				hdExtension = "4x"; 

to this, by itself, just makes everything super tiny on iPad3’s display:

	isHD = true;
				scaleFactor = 2; //scaleFactor = 4
				hdExtension = "2x"; //hdExtension = "4x";

The quick fix here seems to be to republish from Unity installed on a machine w/ OS X 10.6.8. Your Unity license allows up to 2 installs per license. Remember, that operating system upgrades on the same machine count as “an install” in this case. If you’ve reached your limit, you can email Unity’s support and ask to deactivate one machine associated with your email address. They seem to be able to do it within a day or so. Then you can install on a new machine as needed. Not pretty, but an option.

Long term, you have to either add a 4x sprite sheet or update code to auto scale your UI.

Unity3D for Android: Using a Native Java Plugin to Grab the Android Device ID

The java code returns an MEID (Android Device ID) on CDMA phones (Verizon, Sprint), an IMEI on GSM phones (AT&T, T Mobile) and an Android ID on WIFI-only devices (no cellular network).

This code is based on Android Java Plugin for Unity example project in the Unity manual.

Why bother with a plugin?

I tried using Unity 3.5’s built-in SystemInfo.deviceUniqueIdentifier getter for obtaining a unique device ID but it didn’t meet our ad network’s requirements.

The set up in Unity 3.5

  • Drag the AndroidJava.jar file inside /Assets/Plugins/Android/. /Assets/Plugins/Android/bin/ worked too. This .jar file is created via Eclipse or command line javac based on the Java source code
  • Drag the example libjni.so file inside /Assets/Plugins/Android/. Make sure it’s inside /Plugins/Android or you’ll get a “DllNotFoundException: jni” error when you test on device with adb.
  • Drag JNI.cs into /Assets/Plugins/
  • Drag JavaVM.cs into /Assets/Plugins/
  • Make sure your project has an AndroidManifest.xml file inside /Assets/Plugins/Android/ with android.permission.READ_PHONE_STATE permission set. android.permission.READ_PHONE_STATE is needed to access an Android phone/tablet’s Android ID, IMEI or MEID. If you’re making HTTP calls you’ll also need additional permissions, etc.

Code that worked:

...
	private static IntPtr	JavaClass; 
	private static int		GetDeviceId;
...

	///if you're calling the plugin from a static method, you still have to make sure an instance of this script is attached to 
	///an empty GameObject in Hierarchy so Start() method runs & the below code initializes:	
	void Start() {
		
		#if UNITY_ANDROID 		
		
			// attach our thread to the java vm; obviously the main thread is already attached but this is good practice..
			JavaVM.AttachCurrentThread();
			
			// first we try to find our main activity..
			IntPtr cls_Activity		= JNI.FindClass("com/unity3d/player/UnityPlayer");
			int fid_Activity		= JNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;");
			IntPtr obj_Activity		= JNI.GetStaticObjectField(cls_Activity, fid_Activity);
			Debug.Log("obj_Activity = " + obj_Activity);		
			
			// create a JavaClass object...
               //"com/yourCompany/yourProjectName" should be your Bundle ID in Unity's Player Settings & should be the package name in your Java class
			IntPtr cls_JavaClass	= JNI.FindClass("com/yourCompany/yourProjectName/JavaClass"); 	
			int mid_JavaClass		= JNI.GetMethodID(cls_JavaClass, "<init>", "(Landroid/app/Activity;)V");
			IntPtr obj_JavaClass	= JNI.NewObject(cls_JavaClass, mid_JavaClass, obj_Activity);
			Debug.Log("java Helper object = " + obj_JavaClass);		
			
			// create a global reference to the JavaClass object and fetch method id(s)..
			JavaClass					= JNI.NewGlobalRef(obj_JavaClass);
			GetDeviceId					= JNI.GetMethodID(cls_JavaClass, "GetDeviceId", "()Ljava/lang/String;");
			Debug.Log("JavaClass global ref = " + JavaClass);
			Debug.Log("JavaClass GetDeviceId method id = " + GetDeviceId);						
		
		#endif			
	}	
...

	/// <summary>
	/// Gets the unique device for Android devices (IMEI, MEID or Android ID).
	/// </summary>
	/// <returns>
	/// Returns the id as a string.
	/// </returns>
	private string GetTheDeviceID()
	{		
		//didn't work... supposed to return IMEI but didn't 
		//return SystemInfo.deviceUniqueIdentifier;
		
		String dID = "";
		
		#if UNITY_ANDROID 
	
			// again, make sure the thread is attached..
			JavaVM.AttachCurrentThread();
						
			// get the Java String object from the Helper java object
			IntPtr str_cacheDir 	= JNI.CallObjectMethod(JavaClass, GetDeviceId);
			Debug.Log("str_cacheDir = " + str_cacheDir);		
			
			// convert the Java String into a Mono string
			IntPtr stringPtr = JNI.GetStringUTFChars(str_cacheDir, 0);
			Debug.Log("stringPtr = " +stringPtr);
			dID = Marshal.PtrToStringAnsi(stringPtr);
			JNI.ReleaseStringUTFChars(str_cacheDir, stringPtr); 		
					
		#endif

		Debug.Log(" Device ID value is = " + dID);
		
		return devID;		
	}		

/// call GetTheDeviceID() when you need to use it
...

The Java Code

The below code is based on requirements by ad networks that need to use a specific device ID for metrics like conversion tracking. It’s the main source file for generating the AndroidJava.jar you need to import into Unity’s Plugins folder.

The Device ID & hashing methods implementations come directly from Millennial Media‘s public wiki.

package com.yourCompany.yourProjectName;

import android.app.Activity;
import android.content.Context;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaClass
{
	private Activity mActivity;
	
	public JavaClass(Activity currentActivity)
	{
		Log.i("JavaClass", "Constructor called with currentActivity = " + currentActivity);
		mActivity = currentActivity;
	}
	
	public String GetDeviceId()
	{		
		// Get the device ID
        String auid = android.provider.Settings.Secure.ANDROID_ID + "android_id";
        
        Context context = mActivity.getApplicationContext();
        
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        if(tm != null)
        {
             try{
             auid = tm.getDeviceId();
             }
             catch (SecurityException e){
                  e.printStackTrace();
             }
             tm = null;
        }
        if(((auid == null) || (auid.length() == 0)) && (context != null))
             auid = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        if((auid == null) || (auid.length() == 0))
             auid = null;
        
        return auid;	
	}
	
	public String GetHashedDeviceIdSHA1()
	{
		String deviceId = GetDeviceId();
		
		String hashedDeviceId = hashInputSHA1(deviceId);
		
		return hashedDeviceId;
	}
	
	public String GetHashedDeviceIdMD5()
	{
		String deviceId = GetDeviceId();
		
		String hashedDeviceId = hashInputMD5(deviceId);
		
		return hashedDeviceId;
	}

	
	/**
     * <p>
     * Hashes the given plain text using the MD5 algorithm.
     * </p>
     * 
     * <p>
     * Example:
     * </p>
     * 
     * <p>
     * 098f6bcd4621d373cade4e832627b4f6
     * </p>
     * 
     * @param input
     *            The raw input which must be hashed.
     * @return A String representing the MD5 hashed output.
     */
    public static String hashInputMD5(String input)
    {
        String rv = null;
          
        if (input != null)
        {
            try
            {
                // Hash the user ID
                byte[] hashBytes = null;
                MessageDigest md = MessageDigest.getInstance("MD5");
                  
                synchronized (md)
                {
                    hashBytes = md.digest(input.getBytes());
                }
                 
                // Convert the hashed bytes into a properly formatted String
                if (hashBytes != null)
                {
                    StringBuilder sb = new StringBuilder();
                    
                    for (byte b : hashBytes)
                    {
                        String hexString = Integer.toHexString(0x00FF & b);
                        sb.append((hexString.length() == 1) ? "0" + hexString
                                                           : hexString);
                    }
                         
                    rv = sb.toString();
                }
            }
            catch (NoSuchAlgorithmException exception)
            {
                // This exception should never occur
            }
        }
         
        return rv;
    }
    
    /**
     * <p>
     * Hashes the given plain text using the SHA-1 algorithm.
     * </p>
     *
     * <p>
     * Example:
     * </p>
     *
     * <p>
     * a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
     * </p>
     *
     * @param userId
     *            The raw input which must be hashed.
     * @return A String representing the SHA-1 hashed input.
     */
    public static String hashInputSHA1(String input)
    {
        String rv = null;
          
        if (input != null)
        {
            try
            {
                // Hash the user ID
                byte[] hashBytes = null;
                MessageDigest md = MessageDigest.getInstance("SHA1");
             
                synchronized (md)
                {
                    hashBytes = md.digest(input.getBytes());
                }
              
                // Convert the hashed bytes into a properly formatted String
                if (hashBytes != null)
                {
                    StringBuilder sb = new StringBuilder();
              
                    for (byte b : hashBytes)
                    {
                        String hexString = Integer.toHexString(0x00FF & b);
                        sb.append((hexString.length() == 1) ? "0" + hexString
                                                           : hexString);
                    }
                 
                    rv = sb.toString();
                }
            }
            catch (NoSuchAlgorithmException exception)
            {
                // This exception should never occur
            }
        }
             
        return rv;
    }
}

AndroidManifest.xml

If you don’t specify the correct permissions for your app and try to do things like make an HTTP request or grab the Device ID, you’ll get an error, like this:

10-02 15:06:49.223  7776  7784 W System.err: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10109 nor current process has android.permission.READ_PHONE_STATE.
10-02 15:06:49.223  7776  7784 W System.err: 	at android.os.Parcel.readException(Parcel.java:1322)
10-02 15:06:49.223  7776  7784 W System.err: 	at android.os.Parcel.readException(Parcel.java:1276)
10-02 15:06:49.223  7776  7784 W System.err: 	at com.android.internal.telephony.IPhoneSubInfo$Stub$Proxy.getDeviceId(IPhoneSubInfo.java:150)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:216)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.yourCompany.yourProjectName.JavaClass.GetDeviceId(JavaClass.java:44)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.unity3d.player.UnityPlayer.onDrawFrame(Unknown Source)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1363)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)

I grabbed the default one from inside Unity.app on my Mac:

/Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidDevelopmentPlayer/AndroidManifest.xml

Kept all as is, just added my permissions and it worked:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
	android:installLocation="preferExternal"
    android:versionCode="1"
    android:versionName="1.0">
    <supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        android:anyDensity="true"/>

    <application
		android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:debuggable="true">

        //...

    </application>

	
	<!-- PERMISSIONS -->
		<uses-permission android:name="android.permission.INTERNET"/>
		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
		<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
	
</manifest>

Some Other Possible Errors

Here’s a fun one, based on a dumb mistake I made. I put the libjni.so into the wrong folder, /Assets/Plugins/, instead of /Assets/Plugins/Android/:

10-02 14:43:17.147  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.147  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.155  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.163  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.171  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.171  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.179  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.186  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.897  1410  1410 I wpa_supplicant: WPS-AP-AVAILABLE 
10-02 14:43:17.905  1320  1411 V WifiMonitor: Event [WPS-AP-AVAILABLE ]
10-02 14:43:17.905  1320  1411 D WifiMonitor: WPS Event: WPS-AP-AVAILABLE 
10-02 14:43:18.264  1391  1391 D RadioSignalLevel: evdo dbmLevel: 4, snrLevel: 3
10-02 14:43:18.522  7587  7596 I Unity   : DllNotFoundException: jni
10-02 14:43:18.522  7587  7596 I Unity   :   at (wrapper managed-to-native) JavaVM:AttachCurrentThread ()
10-02 14:43:18.522  7587  7596 I Unity   :   at MyUnityDeviceIdScript.Start () [0x00000] in <filename unknown>:0 
10-02 14:43:18.522  7587  7596 I Unity   :  
10-02 14:43:18.522  7587  7596 I Unity   : (Filename:  Line: -1)
10-02 14:43:18.522  7587  7596 I Unity   : 
10-02 14:43:21.561  7587  7596 I Unity   : checkDeviceID() called
10-02 14:43:21.561  7587  7596 I Unity   :  
10-02 14:43:21.561  7587  7596 I Unity   : (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 43)
10-02 14:43:21.561  7587  7596 I Unity   : 
10-02 14:43:21.671  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.694  7587  7596 I Unity   : DllNotFoundException: jni
10-02 14:43:21.694  7587  7596 I Unity   :   at (wrapper managed-to-native) JavaVM:AttachCurrentThread ()
10-02 14:43:21.694  7587  7596 I Unity   :   at MyUnityDeviceIdScript.GetUniqueDeviceID () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :   at MyUnityDeviceIdScript.callTheUrlWithDeviceIDParam () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :   at GameManager.checkDeviceID () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :  

As far as I’ve seen, this code only works on a device. If you try to test inside Unity, you’ll get a similar error:

DllNotFoundException: jni
MyUnityDeviceIdScript.Start () (at Assets/Scripts/MyUnityDeviceIdScript.cs:21)

Once you test on a device, if all else if good, this error should go away.

NOTE: looks like this code requires some time to load up the JNI .so file. Not absolutely sure yet, but it appears if I have a fairly complex project and I try to call a JNI related method very soon after app loading, the app crashes with weird mystery output in adb logcat. Need to look into this more to be sure about the details.

Unity3D for Android: “JNI ERROR (app bug): attempt to use stale global reference” with Incorrect Use of Prime31’s Social Networking Plugin

I was porting a Unity3D-built iOS game to Android the other day, while using the awesome Social Networking plugin from Prime31, and got this fun Java error:

E/dalvikvm( 5539): JNI ERROR (app bug): attempt to use stale global reference 0x32
E/dalvikvm( 5539): VM aborting
F/libc    ( 5539): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 5583 (UnityMain)
... 

The above error crashed my app consistently.

I was lucky in this case because I was fairly sure where it’s coming from, suspecting an unnecessary call to FacebookAndroid.logout() inside a check for !FacebookAndroid.isSessionValid() check. Not my proudest coding moment, for sure.

Once I put a Debug.Log() right before the FacebookAndroid.logout() call and right after. The error changed to… or perhaps a new error started showing up around the same place in the debug log:

W/dalvikvm( 2910): threadid=9: thread exiting with uncaught exception (group=0x4001d5a0)
E/AndroidRuntime( 2910): FATAL EXCEPTION: GLThread 10
E/AndroidRuntime( 2910): java.lang.NullPointerException
E/AndroidRuntime( 2910): 	at com.prime31.FacebookPlugin.logout(FacebookPlugin.java:187)
E/AndroidRuntime( 2910): 	at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
E/AndroidRuntime( 2910): 	at com.unity3d.player.UnityPlayer.onDrawFrame(Unknown Source)
E/AndroidRuntime( 2910): 	at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1363)
E/AndroidRuntime( 2910): 	at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)
W/ActivityManager( 1323):   Force finishing activity com.companyName.MyBundleIDHere/com.unity3d.player.UnityPlayerNativeActivity

The app stopped crashing but the java.lang.NullPointerException didn’t go away either. Still looking into it.

Unity3D for iOS: “Apple LLVM Compiler 3.0 Error”… “iPhone_target_Prefix.pch’ has been modified since the precompiled header was built”

The Error

I upgraded to the latest minor version of Unity 3.5, specifically 3.5.5f. All was fine until I tried to create an Archive so I could publish an .ipa file from Xcode. Once I hit Product > Archive >, I got Build Failed with this error:

Apple LLVM Compiler 3.0 Error:
fatal error: file '/YourPathToProject/YourProjectName/Classes/iPhone_target_Prefix.pch' has been modified since the precompiled header was built

The Solution

After trying to Clean the project & a few other things, nothing worked. Finally, found this stackoverflow solution that fixed it. The Library folder path for the folder that had to be deleted was under
/YourUserName/Library/Developer/Xcode/DerivedData/{project name + gobly-gook}.

Unity3D for Android: Porting a Unity3D iOS Project to Android

This is a Notes-To-Self work in progress. Why share? Several reasons, among them, my desire to see Unity become a more popular platform for mobile app development in the near future. If any part of this post saves someone dev time or helps them pick Unity as the dev platform for their mobile project, that means more work opportunities for developers that took the time to learn Unity.

Basic checklist

  • For on-device debugging, add Android’s adb tool to your environment variable. For me, on OS X, it was fairly easy.
  • Set up logcat w/ adb to get on-device debugging on Android. Xcode’s Console lets you do this pretty much by default when you “Run” on a device that’s attached to your machine via USB.
  • Enable your Android phone for development & USB debugging.
  • Figure out an approach for dealing with the numerous Android pixel densities & screen sizes. Daniel Brauer’s DisplayMetricsAndroid class looks pretty good. Haven’t tested enough yet. As a commenter states, it’s implemented like a “plugin” via the Plugins folder in your project’s Assets folder. Then there’s Screen.dpi, in, at least, Unity 3.5.
  • If you’re using Prime31 plugins like Etcetera and Social Networking, you’ll need to get the Android versions. Their Google Analytics plugin works on both.
  • If you’re using the open source UIToolkit for menus, screens, HUD, etc, look into how to get 1.5x graphics to work. Perhaps, 1.5x sprite sheet and tweak(s) to or subclasses of the UI or UIToolkit classes. Not sure yet.
  • The ProgressDialog is Android’s version of the Activity indicator, UIActivityIndicatorView on iOS.

Potentially useful formulas & numbers

A review aspect ratio formula might come in useful. For example, if you have a screen that’s “1280 x 720”, you can assume width/height = 1280/720 = 1.78 = 16/9, aka it’s a 16:9 aspect ratio. This calculator can be useful at times.

  • So, for HTC Legend’s 480×320, you can do 480/320 = 1.5 = 3/2 to get an aspect ratio of 3:2.
  • For Motorola Droid’s 854 x 480 – 854/480 = 1.78 (1.779) = 16/9 (roughly) yields a 16:9 ratio.
  • For Nexus One’s 800 x 480, do 800/480 = 1.6 (1.666) = 16/10 (roughly) to get 16:10 aspect ratio.
  • Samsung Galaxy S3 is at 1280×720, with a 16:9 ratio.
  • Most Galaxy S2 phones are at 800×480, 16:10 ratio. At least one is at 1280×720, 16:9 ratio.
  • iPad 3 has the horizontal dimensions of 2048 Ă— 1536. 2048/1536 = 1.33, which is roughly 3/2. 3:2 aspect ratio

So if I’m using sprite sheets w/ UIToolkit, does this mean I should create android versions of the sprite sheets at 1.5x, 1.78x and 1.6x versions of the basic size of the smallest iOS images (sheets)? Mmmmm… more research needed.

Try Using Density Independent Pixels via Unity’s Screen.dpi

Screen.dpi is one of the improvements in Unity 3.5 (or from what I hear, even 3.4). If you’re using UIToolkit, you can try using public methods like pixelsFromTopLeft( float x, float y) coupled with the Density-independent pixel technique recommended by the Android developer guide:

Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.
The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a “medium” density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application’s UI, to ensure proper display of your UI on screens with different densities.

So to get the x, y values for the pixelsFromTopLeft( float x, float y) method, use the formula px = dp * (Screen.dpi / 160), assuming 160 dpi is your minimally supported screen dpi. This also means that dp = px / (Screen.dpi / 160).

Note, on some Android devices the system fails to generate a dpi and returns a ZERO. In those cases, the above formula breaks, as noted here.
Here’s a free DP to PS calculator.

SD / HD screen sizes for Android, UIToolkit Sprite Sheets & PSDs

In 2012, 800×480 seems like the most common Android resolution for phones. I’ve heard some rumors on forums w/ no links to sources. Any sources I find, I’ll post here:

For UIToolkit, 800×480 can be our SD resolution and the size we should create the first sprite sheet for. So the .PSD files should be created at 16:10 aspect ratio for 800×480, or the SD UIToolkit sprite sheet in Unity.

I personally don’t care about the low density older Android phones – since I’m making 3D games using Unity, those phone’s processors & memory probably won’t be able to handle my app anyway, so why waste time on creating yet another sprite sheet for it?

Depending on whether or not you care about all of Android’s aspect ratios, supporting slightly older Android tablets or only the latest ones, or just the latest high density phones, you can set your UIToolkit HD sprite sheet(s) to, for example 1280×720 for the latest 2012 Samsung phones like the Galaxy SIII. Using 1280×720 or slightly less like 1160×720 to catch devices like the Galaxy Nexus phone, seems to also work on a few Android tables (like Motorola’s).

Remember, and prep your Designers for this ahead of time, it won’t look pixel perfect on every device. Android device screen size fragmentation is probably worse to deal with than cross-browser CSS problems (yes, even with IE6,7.8 vs the standards browsers on Mac and PC). Gently, remind Designers that an Android layout is not a PSD, PDF, an InDesign file or a printed page.

Some common Android phones with the medium 800×480, or the very close 854×480, screen size:

  • HTC Inspire 4G
  • Motorola DroidX
  • HTC Evo 4G

Sprite sheet problem

UIToolkit worked mostly well for iOS with 3 large, full-screen-sized background images even fitting inside the regular (SD) and 2x (HD) sprite sheet at 2048×2048 in TexurePacker Pro.

I just tried using a similar approach for Android and ran into a wall. The 2x sprite sheet is a problem – if for 2x, I’m sizing my graphics for HD Android phones like the Galaxy SIII at 1280×720… those 3 full-screen-sized background images don’t fit anymore inside 2048×2048. From what I’ve heard on the Unity forums Android has problems with images (sprite sheets) larger than 2048×2048. It’s not ideal, but I guess I can always proportionally scale those down for the sprite sheet and then use Screen.width and Screen.height to scale them. Given the client approved design, it’s nearly impossible, not to have them. The other approach would be to add a second sprite sheet, may be one for buttons & smaller UI stuff and one for unavoidable large background images. This will increase production time since extra sprite sheets will need to be created for SD and HD resolutions. & you’ll need to be careful which sprite sheet you’re targeting when from code.

Some Android-related posts on the main UIToolkit forum thread

Testing in Unity’s Game panel

  • To fake the 1280×720 screen size of the Samsung Galaxy SIII and similar new phones, switch the Game panel’s aspect ratio to Android Wide (16:10) and then stretch the panel till it approximates those dimensions. You can test them in the Console via Screen.width & Screen.height or use something like Screen Ruler or a PSD that’s at that size to approximate. Note: 1280×720 is actually 16:9, the 16:10 Android devices at that size are 1280×800, so keep that in mind.

On-device testing

  • I had trouble with “adb devices” not recognizing an HTC Inspire 4G and then a Motorola DroidX. I googled the crap out of it, read through every post on http://forum.xda-developers.com/ and still nothing. Then I borrowed a USB cable from a coworker who had an Android phone & boom! everything magically worked: adb devices listed both phones, Unity3D was able to publish directly to the device via “Build & Run”. Fun times.

PlayerPrefs.txt & Releasing Updates to iOS & Android Apps

  • Android: Looks like if you release an update to your app via Google Play, your PlayerPrefs.txt file will not be overwritten. I was able to confirm this from my own experience with a Google Play app.
  • Same deal for iOS, looks like an App Store update doesn’t overwrite PlayerPrefs.txt. I was able to confirm this from my own experience with a Unity3D-built app in Apple’s App Store.
  • Some Stuff About Google Play Sucks

    • If you’ve uploaded a new version of your app (a new APK), realize that this version has a bug, and decide to revert to the previous version, you can’t. Google Play doesn’t allow it as of October, 2012. If you’re the developer, you can compile your older source code with a newer Version Code (versionCode) and upload it as a NEWER APK and overwrite the problematic version. What a waste of my time!

    Unity3D for iOS: Storing a New High Score in Parse via UniParse while Adding a Value to a _ptr Field

    So far this is the only way I’ve been able to successfully do this. I wonder if I’m missing something & there’s actually a better way to do this using only 1 call to Parse. Anyone? Feel free to prove me wrong. Please.

    ...
    // localStorage is a PlayerPrefs instance that lets us grab values stored on the device that's running the app
    ...			 
    
    // MyGameUsers is a Parse Class that stores unique user ID's as the parse Class' objectId's
    // change MyGameUsers to your own Class name where appropriate.
    var usersTablePointer = new ParseClass("/classes/MyGameUsers");
    
    //"f2H4saD8" is an arbitrary value for demo purposes, a typical objectId from a Parse table  
    string myQuery = "where={\"objectId\": \""+ "f2H4saD8" + "\" }";             				
    			
    ParseInstanceCollection prseList = gamerTablePointer.List(myQuery);		
    
    //wait to get the Gamer object w/ our objectID specified in myQuery 
    while(!prseList.isDone) yield return null;
    			
    ParseInstance[] items = prseList.items;		
    				
    // post a new record to the Score table in Parse:
    // change MyGameScores to your own Class name where appropriate.
    var myGameScoresClass = new ParseClass("/classes/MyGameScores");
    
    //create a new record in the db table (represented by the ParseClass)
    var myNewScore = myGameScoresClass.New();
    
    //1034 is just an arbitrary score value; you can grab it from your own variable value			
    myNewScore.Set( "Score", 1034 ); 	
    myNewScore.Set( "MyGameUsers_ptr", items[0] as object );
    
    //create the new record in the server side Parse Class (table) called "MyGameScores" (or your own class name)
    myNewScore.Create();
    				
    //Wait until it's finished the save in Parse.
    while(!myNewScore.isDone) yield return null;						
    
    Debug.Log("myNewScore is done; check it in the MyGameScores table in the relevant Parse.com account.");		 
    

    Unity3D for iOS: ParseInstance.GET(string) throws “InvalidCastException: Cannot cast from source type to destination type” for Date objects from Parse

    The Error

    //UniParse boiler plate:
    var pObj = new ParseClass("/classes/Tournaments");			
    string query = "...your query here..."; 	
    ParseInstanceCollection MyParseList = pObj.List( query );			
    while(!MyParseList.isDone) yield return null;					
    ParseInstance[] items = MyParseList.items; 		
    
    //get custom Date from a Parse.com Class (database table)
    string MyDateFromParse = items[0].Get<string>("MyCustomDate"); 
    

    The last line above throws this error because MyCustomDate is of type “date” in the Parse class:

    /*
    InvalidCastException: Cannot cast from source type to destination type.
    ParseInstance.Get[String] (System.String key) (at Assets/Plugins/ParseClass.cs:238)
    MyManager+<getMyCustomDateFromParse>c__Iterator15.MoveNext () (at Assets/Scripts/MyManager.cs:9)				
    */
    

    The Solution

    Read up on Data Types in Parse.com’s documentation.

    Hashtable d = (Hashtable)items[0].Get<object>("MyCustomDate");
    string MyDateFromParse = d["iso"];