Tag Archives: using java code in unity

Unity 3D: Displaying a Fluct (Zucks AdNet) banner in a Unity Android game

Tutorial how to display an Fluct (Zucks AdNet) banner in an existing Unity Android project scene

Seems like using a simple Android JAR files inside a Unity Android project is not such a simple thing to do. I finally managed to get Zucks AdNet working in an existing Unity Android game. For this example I was using Unity for Windows version 3.5.2 and the latest Android plugin for Eclipse.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Register for an account at the Fluct website and download the ZucksAdnetSDK.jar file. In my example I am using version 1.1.3 of Fluct/ZucksAdnet.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the ZucksAdnetSDK.jar file into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • Create a class called ZucksUnityActivity.java. The class will look like this:

    package my.android.game;
    
    import net.zucks.zucksAdnet.sdk.ZucksAdnetUserInfo;
    import net.zucks.zucksAdnet.sdk.ZucksAdnetView;
    import android.os.Bundle;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class ZucksUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void showBanner() {
    
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    
    				ZucksAdnetUserInfo userInfo = ZucksAdnetUserInfo.getInstance(UnityPlayer.currentActivity.getApplicationContext());
    				userInfo.setGender(0); // 0 = male, 1 = female
    				userInfo.setAge(28);
    
    				// And this is the same, but done programmatically
    				LinearLayout layout = new LinearLayout(UnityPlayer.currentActivity.getApplicationContext());
    				layout.setOrientation(LinearLayout.VERTICAL);
    				
    				// DEFINE HERE IF THE BANNER SHALL BE DISPLAYED ON TOP OR ON BOTTOM OF THE SCREEN
    				layout.setGravity(Gravity.BOTTOM);
    				UnityPlayer.currentActivity.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    				ZucksAdnetView zucksView = new ZucksAdnetView(UnityPlayer.currentActivity);
    				layout.addView(zucksView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    			}
    
    		});
    
    	}
    
    }
    

    It’s important that you are using the ZucksAdnetUserInfo object. When I tried it without using this class the banner did not show up. The class extends UnityPlayerActivity instead of Activity. Also we created the static function showBanner() and left the onCreate() function nearly empty. Also we have to wrap the whole content of this function into

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    otherwise we would get an error or a crash in Unity when we call the function. Also some content inside that function is a bit different in order to make it work with Unity.

  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Now we have to add that plugin into Unity.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the ZucksAdnetSDK.jar file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	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">
    		
    		<!-- FLUCT/ZUCKS SDK -->
    		<meta-data android:name="MEDIA_ID" android:value="000000999"  />
    						
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
                <meta-data android:name="android.app.lib_name" android:value="unity" />
                <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
    		<activity android:name="my.android.game.ZucksUnityActivity"></activity>	
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    

    Replace the value of MEDIA_ID in the manifest file with the ID you received on the Fluct website when you registered. Also make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • To finally display the ad banner inside a scene of your Unity Android game create or modify a C# script with the following content:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass ZucksAdnetSDKJavaClass;
    	
    	void Start() {
    		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize Fluct/ZucksAdnetSDK
    			ZucksAdnetSDKJavaClass = new AndroidJavaClass("my.android.game.ZucksUnityActivity");
    			
    			// ZucksAdnetSDK display banner
    			ZucksAdnetSDKJavaClass.CallStatic("showBanner");
    		}
    		
    	}
    }
    

    The banner will now be displayed either at the top or bottom of your phone’s screen depending on what you defined in the source code in the Eclipse project. Note that this code will only be executed on an actual Android device and the banner will not show up in the Unity player! „showBanner“ has to be identical to the function name you were using inside your Eclipse project.

  • If the Unity Android game crashes when you are trying to display a Fluct banner check the error log. If the error has anything to do with a missing database table „tbl_user_info“ then open the ZucksAdnetSDK.jar file with WinZip or WinRAR and copy all the *.sql files from the /assets folder to the /Plugins/Android/assets folder in your Unity Android project and try again.

In the end the screen will look similar like in this screenshot on the right side.

Well that’s all! I hope the tutorial helped you getting Smaad working in your game! Please leave your comments and questions below.

Unity 3D: Integrating Smaad SDK „More Games“ Android Activity in a Unity Android game

Tutorial on how to integrate Smaad SDK in a Unity Android game

This is a tutorial on how to implement Smaad SDK in a Unity Android project. Smaad SDK is some sort of a Japan-only equivalent of Tapjoy and also displays a full screen Activity with a list of „other apps“ for the user to check out. I’m using Smaad SDK for this example because I had to implement this for a customer project.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Register for an account at the Smaad website and download the Smaad JAR file.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the Smaad JAR file (the name of it might be MoreApps.jar) into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • To test if the ads are being displayed we first create a regular Android class called SmaadActivity.java. The content of this class looks like this:

    package my.android.game;
    
    import jp.gmotech.MoreApps.MoreAppsActivity;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    
    public class SmaadActivity extends Activity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    
    		Intent i = new Intent(getApplication(), MoreAppsActivity.class);
    		i.putExtra("MoreAppsZoneId", "11111111"); // YOUR ZONEID HERE
    		startActivity(i);
    	}
    	
    }
    

    Make sure to change the value of „MoreAppsZoneId“ to your own ZoneId you received from the Smaad website.

  • Update the AndroidManifest.xml file that it looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="7" />
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            
            <activity
                android:name="my.android.game.SmaadActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="jp.gmotech.MoreApps.MoreAppsActivity"
                android:configChanges="orientation"
                android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                </intent-filter>
            </activity>
    		
    		<service android:name="jp.gmotech.MoreApps.MoreAppsIntentService" />
        </application>
    
    </manifest>
    

    It’s important that you also add the activity „jp.gmotech.MoreApps.MoreAppsActivity“ to the manifest file since this is being used by Smaad.

  • Build and run the app on your Android phone and you should see the Smaad „more apps“ being displayed. If you don’t see this please refer to the official Smaad tutorials on how to implement this view into the Android app. Once this works continue with this tutorial.
  • Create a class called SmaadUnityActivity.java. You can use your previously created SmaadActivity.java class as a base. The class will look like this:

    package my.android.game;
    
    import jp.gmotech.MoreApps.MoreAppsActivity;
    import android.content.Intent;
    import android.os.Bundle;
    
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class SmaadUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void showSmaadMoreGamesScreen() {
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    				Intent intent = new Intent(UnityPlayer.currentActivity.getApplicationContext(), MoreAppsActivity.class);
    				intent.putExtra("MoreAppsZoneId", "11111111"); // YOUR ZONEID HERE
    				UnityPlayer.currentActivity.startActivity(intent);
    			}
    
    		});
    	}
    
    }
    

    Make sure to change the value of „MoreAppsZoneId“ to your own ZoneId you received from the Smaad website. This class extends UnityPlayerActivity instead of Activity in order to make it work inside Unity. Also we created the static function showSmaadMoreGamesScreen() and left the onCreate() function nearly empty. To make it work inside Unity we have to wrap the whole content of the function showSmaadMoreGamesScreen() into these lines of code:

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    If we don’t do this we would get an error or even a crash in Unity when we call this function. Also some content inside that function is a bit different in order to make it work with Unity. Please have a careful look at the above code.

  • Not entirely sure if the following step is needed but just do it anyways: Add this line to the AndroidManifest.xml file inside the „application“ tags:
    <activity android:name="my.android.game.SmaadUnityActivity" android:screenOrientation="portrait" ></activity>
    
  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Next we have to add the created plugin into Unity.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the Smaad JAR (MoreApps.jar) file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	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">
    
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
                <meta-data android:name="android.app.lib_name" android:value="unity" />
                <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
            <activity android:name="my.android.game.SmaadUnityActivity"></activity>
    		
    		<activity android:name="jp.gmotech.MoreApps.MoreAppsActivity" android:configChanges="orientation" android:theme="@android:style/Theme.NoTitleBar" >
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                </intent-filter>
            </activity>
    
            <service android:name="jp.gmotech.MoreApps.MoreAppsIntentService" />
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    
    

    Make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • Finally we need to create a C# script in Unity to access that Android plugin:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass smaadJavaClass;
    	
    	void Start() {		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize Smaad
    			smaadJavaClass = new AndroidJavaClass("my.android.game.SmaadUnityActivity");
    		}		
    	}
    	
    	void OnGUI () {
    		if( Application.platform == RuntimePlatform.Android ) {
    			if(GUI.Button(new Rect(10, 300, 150, 120), "Show SMAAD Screen")){
    				smaadJavaClass.CallStatic("showSmaadMoreGamesScreen");
    			}
    		}
    	}
    }
    

    Smaad SDK "More Games" activity

    For testing purposes we created a button inside the OnGUI() Unity function. If you press that button the Smaad Activity will be displayed. Note that this code will only be executed on an actual Android device and the button will not show up in the Unity player! „showSmaadMoreGamesScreen“ has to have the same name like the function you were using inside your Eclipse project.

In the end the screen will look similar like in this screenshot on the right side.

Well that’s all! I hope the tutorial helped you getting Smaad working in your game! Please leave your comments and questions below.

Unity 3D: Using Java classes/code

With Unity 3D you can use Java code. Here is a simple example how to use Java classes/code with Unity. Note that this tutorial only works with managed DLL files! If you want to use unmanaged DLL files you best have a look at the tutorial on the Unity 3D page here.

Create the Java class

First we create a Java class for testing:

package android.unity.plugin;

public class MyJava {

public MyJava() {
}

public String sayTokyo() {
return "Tokyo";
}

}

Export it to JAR

Export this class to a JAR file. You can do this with Eclipse in the package explorer by clicking the right mouse button on the class and choose Export -> JAR File. You do notneed to set any special options. Just define your desired dll file name and click export.

Convert it to DLL

Next go to IKVM.NET. Download and install this software. With IKVM you can convert JAR files into DLL files. This is what we need to do in order to be able to use the Java code with Unity.

Make sure to add the /bin path of IKVM to your System Environment Variable. It will look something like this:
C:\Users\de\Development\ikvm-7.0.4335.0\bin

Open a command prompt (CMD) and go to the directory where the previously exported JAR file is located. Then enter following command to convert the JAR file to a DLL file:

C:\Users\de>cd Desktop
C:\Users\de\Desktop>ikvmc -out:MyJava.dll MyJava.jar
C:\Users\de\Desktop>

When this command has been executed you have the MyJava.dll file which now can be used in Unity (this DLL file is a so called „managed dll“ file).

The Unity 3D stuff

Open Unity and import the MyJava.dll to your Assets folder. I copied mine to the Plugins sub folder but as far as I know this is not necessary.

I am not sure if this step is necessary but I did it anyways: Copy all the .dll files from the IKVM folder to the Assets/Plugins folder in Unity.

Create a .cs script – MyManagedJavaPlugin.cs – with Unity with the following content:

using UnityEngine;
using android.unity.plugin;

public class MyManagedJavaPlugin : MonoBehaviour {

void Awake() {
MyJava obj = new MyJava();
print(obj.sayTokyo());
}

}

android.unity.plugin has to be the namespace you used when you created the Java project with Eclipse.

Next you can attach the MyManagedJavaPlugin.cs script to an object in your Unity scene. Hit the play button in Unity and you will see that when the „Awake“ action is happening in Unity the sayTokyo() method will be called. The string „Tokyo“ will then be output in your Unity console.

That’s it for this tutorial. From now on you can modify your script and classes to fit your needs.