Using Unity Android In a Sub View

With the eclipse guide removed from the docs I have updated this to go from start to end in doing this.

First thing is to get your unity project set up and built.
As a basic example just create a spinning cube project then build for android ( obviously ).

The next step is to move some files around.
Go into your project directory and you will see a Temp folder in there you will see a Staging Area folder. You need to copy that folder out with the Temp folder. It doesn’t matter where to but as long as it not in the Temp folder. The reason for this is when you use the unity project in eclipse if you use the staging area in temp folder directly when unity rebuilds it changes the contents and this leads to problems with eclipse.

Now you need to open up eclipse.

Once open create a new android project and select create from existing source and point to the staging area folder that you created. This will give you the unity application in eclipse. I called this UnityLib for ease of reference in the future.

Next thing to do is to make another android project in eclipse.
The two important parts here are to make sure you have the correct API levels and the package name matches that of the package name you gave for the project in unity. I called this Unity Java for ease of reference.

Now we need to change a bunch of settings and move some file around.

  • Right Click UnityLib and select properties. Then under android check IsLibrary, Apply, OK

  • Right Click UnityJava and select properties. Then under Java build Path there are a few things that need to be done

  • First click external jar then navigate to your unity install directory then select Data\PlaybackEngines\androidplayer\bin\classes.jar

  • Then under android you need to add the library UnityLib.

  • now move the folder and their contents under the asset folde rin UnityLIb to the asset folder in UnityJava

  • next move the AndroidManifest from the UnityLib to UnityJava

Now you need to make some small code changes

  • in the main source file in UnityJava you need to extend from UnityPlayerActivity and not Activity.
  • if you press ctrl+shift+O after doing that it will automatically resolve the dependencies
  • next you need to remove the line of code setContentView(R.layout.main);

And that should be it if you now run the UnityJava applicaiton for android it will build and run and you will see your unity content launched through an eclipse project.

Now assuming you have managed that without running into any errors its time to do some work in eclipse.

Repairing the damage we have already caused

  1. The class needs to go back to extending a normal activity and not the unity one.

Creating the Frame Layout We Require

Under the Java part of the project( as I referred to it in the docs ) expand the res folder to res->layout then double click main.xml. You should then see the main.xml open up. Notice there are now two tabs at the bottom one for the graphical layout and the other for the actual xml.
I prefer to do it by manually editing some of the xml to start with. I suspect that by default that a LinearLayout and a Textview will have been created for you in the xml. Delete it all apart from the <?xml version="1.0" encoding="utf-8"?> line. This gives us a blank slate to work on in the much friendlier Graphical Layout tab.
In the Graphical Layout drag a FrameLayout onto the screen area. Then drag another view onto the screen area. This second view can then be resized and will represent the area of the screen where you want the unity player to render.
That’s it for setting up the view.

Gratuitous ScreenShot

The code

A large portion of the code that is being used in here is the same as the code that is being used in the UnityPlayerActivity.java file that you would find in
C:\Program Files (x86)\Unity\Editor\Data\PlaybackEngines\androidplayer\src\com\unity3d\player\

You will need a UnityPlayer variable to start off with.

The Unity Player then needs to be setup

        // Create the UnityPlayer
        m_UnityPlayer = new UnityPlayer(this);
        int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);
	boolean trueColor8888 = false;
	m_UnityPlayer.init(glesMode, trueColor8888);

Then the unity player needs to be allocated to a view to get the player to run.

		// Add the Unity view
		FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);		
		LayoutParams lp = new LayoutParams (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		layout.addView(m_UnityPlayer.getView(), 0, lp);

The important part of this is the line of code:

FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);

This will determine which framelayout we add the view to render unity in.
The “R.id.framelayout2” is and autogenerated file that you can find in the project under the gen folder.

Here is the complete source file:

package com.unity3d.viewexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout.LayoutParams;

import com.unity3d.player.UnityPlayer;


public class JavaCubeViewActivity extends Activity {
	private UnityPlayer m_UnityPlayer;
		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Create the UnityPlayer
        m_UnityPlayer = new UnityPlayer(this);
        int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);
		boolean trueColor8888 = false;
		m_UnityPlayer.init(glesMode, trueColor8888);

		setContentView(R.layout.main);
		
		// Add the Unity view
		FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);		
		LayoutParams lp = new LayoutParams (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		layout.addView(m_UnityPlayer.getView(), 0, lp);
    }
}

Did you just say pics or it didn’t happen.

2 Likes

Thanks Rolf! It seems like this did not get any intention from anyone here on the forums. But I think this could be really helpful to some people.

For my current project I have reverse engineered the above steps. Too bad you did not post it 3 weeks ago :wink:

Anyway, I have a still open question for which I did not found an answer yet. In addition to the above, how would you detect whether or not the Unity view has been fully initialized (Splash screen is gone)? It could make sense in some situation to wait adding native android element, until the scene is present and can be used. I could call something from Unity on a AndroidJavaClass instance myself, but that is not what I prefer to do.

Do you or anyone else has thoughts on that?

Thanks!

Haha yeah it’s something I’ve been sitting on for a while but other commitments got in the way.

Using the AndroidJavaClass would be the best way. Just call something in a start function in a script attached to your main camera in your main scene… that was a mouthfull.

I am not able to integrate unity with eclipse. I donno why I cant but when I do all the steps and run the java project there seems to be an error. its showing invalid apk file

RoflHarris, do you know if the path to the Unity “Data” folder can be overridden on the Android using a custom activity?

I would like to set the engine to look for it’s assets in another path instead that of the application folder and I can’t seem to find any solution to this.

Resource re-package Failed!
package -v -f -m -J gen -M AndroidManifest.xml -S “res” -I “/Users/admin/Public/android-sdk-mac_x86/platforms/android-14/android.jar” -F bin/resources.ap_
Configurations:
(default)

Files:
drawable/app_icon.png
Src: () res/drawable/app_icon.png
values/strings.xml
Src: () res/values/strings.xml
AndroidManifest.xml
Src: () AndroidManifest.xml

Resource Dirs:
Type drawable
drawable/app_icon.png
Src: () res/drawable/app_icon.png
Type values
values/strings.xml
Src: () res/values/strings.xml
Including resources from package: /Users/admin/Public/android-sdk-mac_x86/platforms/android-14/android.jar
applyFileOverlay for drawable
applyFileOverlay for layout
applyFileOverlay for anim
applyFileOverlay for animator
applyFileOverlay for interpolator
applyFileOverlay for xml
applyFileOverlay for raw
applyFileOverlay for color
applyFileOverlay for menu
applyFileOverlay for mipmap
Processing image: res/drawable/app_icon.png
(processed image res/drawable/app_icon.png: 68% size of source)
(new resource id app_icon from drawable/app_icon.png #generated)
AndroidManifest.xml:4: error: Error: No resource found that matches the given name (at ‘icon’ with value ‘@drawable/ic_launcher’).

UnityEngine.Debug:LogError(Object)
PostProcessAndroidPlayer:PostProcess(BuildTarget, String, String, String, String, String, String, BuildOptions)
UnityEditor.HostView:OnGUI()

I am Getting this error.In my Project i dont have any errors but when Build the project i am getting this error. i followed this reference also but i got issue file://localhost/Applications/Unity/Unity.app,
file://localhost/Applications/Unity/Unity.app/Contents/Documentation/Documentation/Manual/Android-Integrating%20Unity%20With%20Eclipse.html /Contents/Documentation/Documentation/Manual/Android-Launch%20an%20Android%20Application%20from%20a%20Unity%20Application.html any help friends how integrate eclipse in unity

Is it possible to make unity view transparent and show it on top of android UI?

1 Like

hi… thx for this… i was trying to make something similar with the qualcomm AR lib… the QCARPlayer in a Subview… Do you have any idea how that could be done? thx…

Hmm… for some reason when the application starts I get an errors saying “Could not find class 'com.unity3d.player.UnityPlayer…” but I’ve referenced the classes.jar in the build settings.

Any help?

Ok, Unity 3.5.1 works!

Any idea how to call C# code from Java? Or just to comunicate with the C# code somehow?

Asse, did it work for you? What did you do? I’m trying with 3.5.2 version and I have the same problem, it crashes after loading. :frowning:

Make sure the checkbox next to the classes.jar file is checked. that tells eclipse to export the file out with the package. I fought with the same problem for the better part of the night.

Hi to all, i made a nice tutorial (4 Parts) how to work with Unity and Eclipse! Check it out here, an send me a feedback please → http://www.youtube.com/watch?v=zxn2CuQszvw

So what i want to do now… i want to start a Webview Activity from a GUI Button and stop the game Activity. And then close the Webview Activity and go back to the game! If somebody knows how to do i can continue the tutorial…it would be nice. :slight_smile:

ok found the solution as framelayout2 isnt the view id but layout id ^^’

<FrameLayout xmlns:android=“http://schemas.android.com/apk/res/android
android:id=“@+id/framelayout2”

thanks anyways…

can you post a sub-view demo project please ? whatever I do, I am getting " Caused by: java.lang.ClassCastException: android.view.View cannot be cast to android.widget.FrameLayout" error :frowning:

main.xml :

<?xml version="1.0" encoding="utf-8"?>

Code:

private UnityPlayer m_UnityPlayer;
private FrameLayout layout;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//Create the UnityPlayer
m_UnityPlayer = new UnityPlayer(this);
int glesMode = m_UnityPlayer.getSettings().getInt(“gles_mode”, 1);
boolean trueColor8888 = false;
m_UnityPlayer.init(glesMode, trueColor8888);
setContentView(R.layout.main);

// Add the Unity view
layout = (FrameLayout) findViewById(R.id.view1);
LayoutParams lp = new LayoutParams (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.addView(m_UnityPlayer.getView(), 0, lp);

}

Hello, i have succesfully done this by following code. (This time sorry i have no time for another video tutorial :frowning: )

A kind of webview start by klicking a button in Unity and brings a view to front of Unity Player…now the problem is to close the webview again. Somebody knows how to do? And maybe also to pause the game? And also make the webview zoomable, because this also doesn’t work?

package com.babyninja.babyninjadance;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MyStartActivity extends UnityPlayerActivity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onBackPressed()
	{
	   // instead of calling UnityPlayerActivity.onBackPressed() we just ignore the back button event
	   super.onBackPressed();
	   Log.d("onBackPressed","onBackPressed");
	}
	
	public static void setupViewStatic() {
		Log.d("setupViewStatic","setupViewStatic");
		
		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
			public void run() {
				
				// And this is the same, but done programmatically
				LinearLayout layout = new LinearLayout(UnityPlayer.currentActivity.getApplicationContext());
				layout.setOrientation(LinearLayout.HORIZONTAL);
				
				// SET HERE IF YOU WANT THE BANNER TO BE DISPLAYED AT THE TOP OR BOTTOM OF THE SCREEN
				layout.setGravity(Gravity.BOTTOM);
				UnityPlayer.currentActivity.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				
				//FIRST positive test
				/*
				TextView text = new TextView(UnityPlayer.currentActivity);
				text.setText("This is an example for the Bright Hub!"); 
				
				layout.addView(text);
				*/
				
				
				
				WebView myWebView = new WebView(UnityPlayer.currentActivity);
				myWebView.getSettings().setJavaScriptEnabled(true);
				myWebView.loadUrl("http://www.asteam.de/game_news_iphone3.php");
				
				myWebView.getSettings().setSupportZoom(true);       //Zoom Control on web (You don't need this if ROM supports Multi-Touch     
				myWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
				myWebView.getSettings().setLoadWithOverviewMode(true);
				myWebView.getSettings().setUseWideViewPort(true);
				
				layout.addView(myWebView);
				
				//AdView adView = new AdView(UnityPlayer.currentActivity);
				//layout.addView(myWebView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

				//adView.setBackgroundColor(0xff000000);
				//adView.setPrimaryTextColor(0xffffffff);
				//adView.setSecondaryTextColor(0xffcccccc);
				
				
			};
		});
		
	}
	
}

Hello i have the code without errors but when i run in logCat i have the follow error:
Could not find class ‘com.unity3d.player.UnityPlayer’, referenced from method com.unity3d.viewexample.JavaCubeViewActivity.onCreate

I had attached the unity library “classes” and I dont know what is wrong, please help me, if finally it works, I will upload the project. :smile:

Thanks all and nice tutorial!


I solved this problem but i have the error:

 E/Unity(604): Unable to locate player settings. bin/Data/settings.xml
 D/AndroidRuntime(604): Shutting down VM
 W/dalvikvm(604): threadid=1: thread exiting with uncaught exception (group=0x40015560)
 E/AndroidRuntime(604): FATAL EXCEPTION: main
 E/AndroidRuntime(604): java.lang.UnsatisfiedLinkError: Couldn't load mono: findLibrary returned null
 E/AndroidRuntime(604): 	at java.lang.Runtime.loadLibrary(Runtime.java:429)
 E/AndroidRuntime(604): 	at java.lang.System.loadLibrary(System.java:554)
 E/AndroidRuntime(604): 	at com.unity3d.player.UnityPlayer.<init>(Unknown Source)
 E/AndroidRuntime(604): 	at com.unity3d.viewexample.JavaCubeViewActivity.onCreate(JavaCubeViewActivity.java:31)
 E/AndroidRuntime(604): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 E/AndroidRuntime(604): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
 E/AndroidRuntime(604): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
 E/AndroidRuntime(604): 	at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 E/AndroidRuntime(604): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
 E/AndroidRuntime(604): 	at android.os.Handler.dispatchMessage(Handler.java:99)
 E/AndroidRuntime(604): 	at android.os.Looper.loop(Looper.java:123)
 E/AndroidRuntime(604): 	at android.app.ActivityThread.main(ActivityThread.java:3683)
 E/AndroidRuntime(604): 	at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(604): 	at java.lang.reflect.Method.invoke(Method.java:507)
 E/AndroidRuntime(604): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)   
 E/AndroidRuntime(604): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 E/AndroidRuntime(604): 	at dalvik.system.NativeStart.main(Native Method)

my code:

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;

import com.unity3d.player.*;


 

 

public class JavaCubeViewActivity extends Activity {

    private UnityPlayer m_UnityPlayer;

        

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Create the UnityPlayer
        m_UnityPlayer = new UnityPlayer(this);
        int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);
        boolean trueColor8888 = false;
        m_UnityPlayer.init(glesMode, trueColor8888);

        setContentView(R.layout.main);

        // Add the Unity view
        FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout2);     
        LayoutParams lp = new LayoutParams (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layout.addView(m_UnityPlayer.getView(), 0, lp);

    }

}

The main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frameLayout2"
    android:layout_width="wrap_content"
	android:layout_height="wrap_content" >

<View
android:id="@+id/view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</FrameLayout>

The error is when try this I think m_UnityPlayer = new UnityPlayer(this);

Just a note that the helpdoc link Rolf mentioned is completely inactive now - and the steps do not seem to work for Unity 3.5.x (though I got it to work back in 3.3.x)

http://unity3d.com/support/documentation/Manual/Android-Integrating%20Unity%20With%20Eclipse.html

Please update!

Hey guys it has been removed from the docs as it was merely a hacky way of doing this and not really an “official” solution. We are working on something that should automate the process for a future release. I am at this very moment working on an updated guide that I will post in the forums. All being well and I don’t get too bogged down today with other things it should be updated later today.

Updated