add adMob banner to your unity3d game using unity2eclipse

a great benefit about using unity2eclipse is the possibility to extend your unity3d projects with native android elements like buttons or layouts. as a practical example we decided to show you the integration of an adMob banner in your game.

first of all you have to create an eclipse project – the easiest way to do that is to use our unity2eclipse plugin of course! ūüėČ click here to learn how to do that.

once created we add the adMob SDK to the project:
right click on the project name, find Properties in the menu (it is located at the very bottom). selecting the properties will open a settings window Рnavigate to Java Build Path -> Libraries -> Add External JARs… select the previously downloaded adMob .jar file and click OK.

Java Build Path -> Libraries -> Add External JARs…

the ugly thing about the latest android SDK update is the requirement to copy the adMob .jar  file manually into the libs folder of your project too. i am not sure if this is a bug or a feature, but adding it twice is the only solution that worked for me. just drag & drop it from your finder/windows explorer into eclipse.

additional location of the adMob .jar file

lets start with the more fun part of the tutorial and create a layout file that contains a placeholder for our unity player and the adMob banner – we’ll name it unitylayout.xml and store in res/layout folder of our project.

create a new layout xml file here

the contents of the XML layout:

<?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/unity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" />

   <com.google.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="useYourIdHere"
        ads:loadAdOnCreate="true" />

</FrameLayout>

(replace the “useYourIdHere” with your adMob ID ūüėČ )
we’ll use a FrameLayout – it will allow us to position widgets on top of each other – in our case the banner view on top of the unity player (learn more about android layouts)

in the next step we’ll adjust the .java class file:
the established way to implement an unity player here is to extend the UnityPlayerActivity:

public class myUnityProject extends UnityPlayerActivity

its fine, but it wont allow you to add any native android widgets to your app. we’ll change it, extend an Activity and push the unity player into the LinearLayout placed in our layout xml file. you can replace the whole content of the class with this code:

public class myUnityProject extends Activity
{	
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unitylayout);
		LinearLayout playerHolder = (LinearLayout) findViewById(R.id.unity);
		UnityPlayer myPlayer = new UnityPlayer(this);
        myPlayer.init(1, false);
		playerHolder.addView(myPlayer.getView());
	}
}

the last file that we need to edit is the Manifest.xml located in the root of our project. adMob SDK requires some permissions in order to be displayed correctly:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="6"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 
            android:name=".myUnityProject"
            android:enabled="true"
            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="com.google.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <meta-data android:name="ADMOB_ALLOW_LOCATION_FOR_ADS" android:value="true" />

</manifest>

i hope that this little tutorial will help you to understand how to extend the functionality of your unity android game and to benefit from adMob integration.

tutorial: passing screen offset values from live wallpaper to unity3d with unity2eclipse

remember! creating android live wallpapers with unity2eclipse is experimental and works with unity 3.4.x!

one great thing about android live wallpapers is the possibility to interact with touch events generated when the user swipes through the home screens – this little tutorial will show you how to move (smoothly) the camera on the X-axis:

rename your camera to “myCam” and add this C# script to it:

using UnityEngine;
using System.Collections;

public class CamController : MonoBehaviour {

	public float scaleFactor = 5f;
	private float camOffsetFactor = 0.5f;
	private Vector3 newPosition;

	void FixedUpdate()
	{
        newPosition = new Vector3((camOffsetFactor - 0.5F) * scaleFactor, transform.position.y, transform.position.z);
        transform.position = Vector3.Lerp(transform.position, newPosition, 0.02F);
	}

	public void SetCamOffsetFactor(string offset)
	{
		camOffsetFactor = float.Parse(offset);
	}
}

 

than find your java class in eclipse…

…and update the onLWPOffsetsChanged method with UnitySendMessage() where:

  • myCam is the name of your unity3d object (in this case our camera);
  • SetCamOffsetFactor is the name of the public method in your C# script;
  • String.valueOf(xOffset) is the current screen offset as string (UnitySendMessage) supports string values as parameter only;
public void onLWPOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset)
{
	UnityPlayer.UnitySendMessage("myCam", "SetCamOffsetFactor", String.valueOf(xOffset));
}

it is always nice to have some easy way to test your LWP in your unity3d editor ūüėČ in this case you can just add this lines into the C# script:

void OnGUI()
{
	GUILayout.BeginHorizontal();
	if(GUILayout.Button("set to 0.0"))
	{
		SetCamOffsetFactor("0");
	}
	if(GUILayout.Button("set to 0.5"))
	{
		SetCamOffsetFactor("0.5");
	}
	if(GUILayout.Button("set to 1.0"))
	{
		SetCamOffsetFactor("1");
	}
	GUILayout.EndHorizontal();
}

click here to download the demo wallpaper from the google play store

Unity2Eclipse and Vuforia

With a  few steps you can use our plugin to swap a unity project + vuforia to Eclipse.

1.You need a working UnityProject + Vuforia.
2.Just follow our instruction to export it to Eclipse.
All you have to do now in Eclipse is:
3. Copy the QCAR folder from  Library
to your assets  folder from your custom Android project.

4. Add QCAR.jar and QCARUnityPlayer.jar to Java Build Path.
You find these at your Library Folder /plugins

5. Also copy both jar files into libs folder.

6. Now copy your Manifest from Library to custom Android Project.

7. At least clean and build your project “Project”–> “Clean” and “Project” –> “Build”.
In some cases you need to fix your properties. Just right click on both projects and select ‚ÄúAndroid Tools‚ÄĚ –> ‚ÄúFix Project Properties‚ÄĚ.
Now choose “Run” –>”Run As” –>”Android Application” from the Eclipse menubar.

 

At the moment you have to do step 3 + normal export each time when you update your Unity project .

Android Live Wallpapers with Unity3d

In the last blog post about creating Android Eclipse projects with Unity3d we introduced our Unity3d editor extension called AJUnity2Eclipse, which makes it possible to create an Android Eclipse project directly in Unity with one single click. During the nearly two weeks in the Unity Asset Store we collected some feedback and feature requests and there was one comment that was in particular quite interesting. One user suggested a feature to make it possible to create Android Live Wallpaper projects instead of a stand alone application project. We wondered if this is possible and did some testing on integrating the unity player into an Android Live Wallpaper Service. After facing some architectural problems and struggling with the event forwarding mechanism we in fact got it working!

Create Android Live Wallpapers with Unity3d and AJUnity2Eclipse

The latest version of AJUnity2Eclipse (available in the Unity Asset Store) provides an option to chose, wether you want to create a stand alone Android application or an Android Live Wallpaper! Please note that this is still an experimental feature that is roughly tested (with the Angry Bots demo that ships with Unity and some of our own projects) and currently only works with Unity3d version 3.4.

If you have any issues or suggestions, please send us feedback to ajunity2eclipse@appjigger.com! Don’t forget to mention your exact Unity3d and Android SDK version, this helps us with bug fixing and to improve AJUnity2Eclipse!

We hope you enjoy the new feature and would like to see some cool 3d Live Wallpaper in the near future! :-)

Unity Editor Plugin for creating Eclipse-Android projects

UPDATE: it is now also possible to create Android Live Wallpapers with Unity3d ‚ÄĒ check out the latest version of AJUnity2Eclipse!

Developing with Unity3d makes a lot of fun, not least because Unity dramatically simplifies the workflow when developing for multiple platforms. This is a huge benefit, especially when developing for different mobile platforms with many different screen sizes and device features. Unity already comes with a great framework to support most of these features. However from time to time, it can be useful to have the ability to write additional native code for a specific platform, namely Android and iOS. For example, we lately developed an app for one of our customers that had the requirement to display a login-screen on startup and user/role management on an additional screen. Of course this could be (somehow) done in Unity, but a native solution was clearly preferred. For iOS this was not a big problem, since Unity builds an Xcode project that can be extended easily. But for Android it was not that simple to get the whole thing to work in Eclipse. If you are familiar with the steps it takes (described here) to make Eclipse and Unity play together, you know how time consuming and error-prone it is. The most annoying part is that you have to copy the contents of the assets folder to your eclipse project, every time you make a change to your Unity project. And it is even worse if you have to integrate everything into your version control system.

Then¬†‚Äď last week¬†‚Äď we got a similar requirement for a new app and we agreed that this was not an optimal solution. So we decided to develop an Unity Editor Plugin that automizes the entire process and comes up with a one-click solution!
The Plugin adds a menu item to Unity to directly create an Eclipse Android project for your unity project. And the best thing: you no longer need to copy the assets folder! Once you continued working in Unity you can update your Eclipse project with one click! Of course this operation preserves any changes you made to the Eclipse project in the meantime.

We packaged the Plugin and made it available in the Unity Asset Store. After downloading, simply follow the instructions in the next section to set it up.

Using the AJUnity2Eclipse Plugin

First of all, download AJUnity2Eclipse Plugin from the Unity Asset Store and directly import it to your project. Alternatively, if you already downloaded a copy, you can simply pick the AJUnity2Eclipse.unitypackage file from your filesystem and drag it to the Project-Window in Unity.

Before your project can be exported to Eclipse, you initially need to make an Android-Build. Go to “File” -> “Build Settings ..”, select Android from the available platforms menu and click “Build”. Unity asks you to save the APK-file somewhere ‚Äď you can save it anywhere, you won’t need it anymore.¬†Once you have done this, click the new menu item named “Eclipse export ..” in the “File”-Menu. A small configuration dialog appears: you can leave all settings unchanged. You might want to change the output directory (the directory, where the Eclipse Projects are created¬†‚Äď yes there are two projects), but we recommend to use the default, since this keeps your project well structured. Now finally click “Create Eclipse project”.

Note that AJUnity2Eclipse respects your Android Player Settinngs, like Bundle Identifier, Bundle Version and Minimum API Level, so your project is already well set up! By default, a directory called “eclipse-android” has been created in the root folder of your Unity project.

Now fire up Eclipse and go to “File” -> “Import…” -> “Android” -> “Existing Android Code into Workspace” and pick the newly created “eclipse-android” folder, or whatever you specified as output directory. By selecting this folder, you already see the two projects in the list box. Check them both and hit “Finish”. Important: it’s strongly recommended to not check the “Copy projects into workspace” option!¬†Otherwise your assets will not be updated automatically when you make changes to the Unity project.

In some situations, you might see a small red exclamation mark in your package explorer or you might get build errors in Eclipse. To solve this issue, right click on the projects and select “Android Tools” -> “Fix Project Properties”.¬†That’s it!

You can now build the Android project (the one that does not include the word “library” in its name) like you would do normally and test it on your device. The library-project includes the Unity Player binary files and is automatically referenced from your main project¬†‚Äď you never have to touch or care about it.

Now you can add Java classes and change the main Activity to whatever you want. If you at any time go back to your Unity project and make some changes, you simply need to make an Android Build an run the export Plugin again. It automatically recognizes that you already created an Eclipse Project and offers you to update it with your latest Unity changes (like assets and scripts).

If you have any problems with the plugin, feel free to contact us or to leave a comment!