Android and Unity Interaction Research

Source: Internet
Author: User

Android and Unity Interaction Research

Reprint Please specify source: http://blog.csdn.net/crazy1235/article/details/46733221

    • Android and Unity Interaction Research
      • The origin of unity and Android interaction
      • Unity Simple Introduction
      • Unity and Android Interactive introduction
        • Unity calls the Android method
        • How Android calls Untiy

The origin of unity and Android interaction

In the project development process, I encountered such a demand, the unity of the scene in the Android to display. It was also confused at first, and unity was never heard of anything. Later also query a lot of information, only to achieve the effect of demand. So put some of their own summary recorded in this, convenient for you peer reference.

Unity Simple Introduction

Unity is a multi-platform integrated game development tool that can develop interactive content such as three-dimensional video games, building models, and three-dimensional animations, with a strong cross-platform . After writing scenes and programs in unity, you can export versions of multiple platforms, such as Android, iOS, Windows Phone, and PC.

For example, lists all the platforms that unity can export.

Unity and Android Interactive introduction

As a general rule, unity is used as part of an Android program to treat a u3d scene as an interface or as part of an interface.
There is also the development of Android as part of unity. But this form of development is rare and unnecessary.

Let's take an example to illustrate the interaction between the two.

First, there's a game scene in unity that runs like this:

In this scenario, "1" is a label that displays the name of the monster character set up from Android. "2" is used to control the size display changes in the Android program. "3" is changed with the size of the test in unity.

Unity calls the Android method

We need to call the Android method after we run the Unity engine and call the method in the Java class to get the name of the monster. Uniy
Unity calls the Java method in a total of four forms, namely:

    • Normal method with no return value
new AndroidJavaObject("android.content.res.Configuration");jo.Call("setToDefaults");
    • Normal method with return value
new AndroidJavaObject("java.lang.String""some string");int hash = jo.Call<int>("hashCode");
    • static method with no return value
new AndroidJavaObject("android.os.Binder");jo.CallStatic("flushPendingCommands");
    • static method with return value
new AndroidJavaObject("java.lang.String");string valueString = jo.CallStatic<string>("valueOf"42.0);

We're going to bind some action –operate.cs to the game object:

usingUnityengine;usingSystem.Collections; Public classOperate:monobehaviour { PublicTransform Target; PublicUILabel label; Public BOOLFlag =true;//   <summary> ///   define rotational speed//   </summary>  Public floatRotatespeed= $;// Use this for in itializationvoidStart () {//debug.log ("Hello");  This. Name ="Manager"; GetData ();}//   <summary> ////   by calling the method in Android to get the name and assigning a value to the label//   </summary> voidGetData () {Androidjavaclass JC =NewAndroidjavaclass ("Com.unity3d.player.UnityPlayer"); Androidjavaobject Jo = JC. Getstatic<androidjavaobject> ("CurrentActivity");stringName = Jo. Call <string> ("GetName","Successful call to Android method"); Label.text = name;}//Update is called once per framevoidUpdate () {//target. Rotate (vector3.up * time.deltatime * rotatespeed);}voidOnClick () {screen.orientation = Screenorientation.landscape;if(flag) {Target.localscale =NewVector3 (0.5F0.5F0.5f); Flag =false;//label.text = "123456";}Else{Target.localscale =NewVector3 (0.75F0.75F0.75f); Flag =true;//label.text = "000000";} }//   <summary>  ///   top off before the scene //   </summary> voidUnload () {Application.loadlevel (1); Androidjavaclass JC =NewAndroidjavaclass ("Com.unity3d.player.UnityPlayer"); Androidjavaobject Jo = JC. Getstatic<androidjavaobject> ("CurrentActivity"); Jo. Call ("Makepauseunity"); }//   <summary> //   Zoom in//   </summary> voidZoomIn () {Target.localscale =NewVector3 (0.75F0.75F0.75f);}//   <summary> //   Reduced//   </summary> voidZoomout () {Target.localscale =NewVector3 (0.5F0.5F0.5f);}}

Once the code and scene have been written, you can use the Unity apk file to run everywhere. But we need to do two development in eclipse, so we need Android engineering everywhere.

When exporting, you can choose to export "Google Android Project".

For example, if this option is not checked, an apk file is exported.
Before you export Android project or APK, you need to do some configuration in "Player Settings":

These configurations are basically consistent with our development settings for tools such as Eclipse.
After exporting the Android project, you see the following directory structure:

    • Assets file below are some of Unity's resource files, including scenes and rendered files.
    • Libs below of course is the jar package and so file.
    • SRC consists of three Java classes. Recommended use of Unityplayeractivity.java

After opening the unityplayeractivity, you will find an instance of Unityplayer in which there is an object, and when we do a nested u3d scene in Android, we add this instance as a view to our layout. .

After exporting Android projects, there are two scenarios:

    • You already have an Android project, just copy the assets files and Libs packages to your project, and configure the classes you need to configure in Androidmanifest.xml.
    • Without engineering, you only need to import the unity export project into your IDE.

Look at the layout of the mainactivity:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Match_parent"android:layout_height="Match_parent"  Android:background="#E0EEE0"android:gravity="Center_horizontal"  Android:orientation="vertical" >                        <!--3D View Area --    <linearlayoutandroid:id= "@+id/u3d_layout"android:layout_width=" Match_parent "android:layout_height=" 300DP"android:background="#a6a9af "  android:orientation="vertical" >                                            </linearlayout>    <!--zoom in    <buttonandroid:id="@+id/zoom_in_btn"android:layout_width="200DP "android:layout_height="wrap_content "android:layout_margintop=" 20DP " android:padding="10DP"android:text="zoom in" />                                                    <!--reduced --    <buttonandroid:id= "@+id/zoom_out_btn"android:layout_width=" 200DP "android:layout_height="wrap_content "android:layout_margintop=" 20DP "  android:padding="10DP"android:text="Zoom Out" />                                                    <!--fullscreen --    <buttonandroid:id="@+id/u3d_fullscreen_btn"android:layout_width= "200DP" android:layout_height="Wrap_content"android:layout_margintop="20DP"  android:padding="10DP"android:text="Full screen" />                                                </linearlayout>

Before pasting the logic code, let's look at how Android calls the Unity method:

Android calls the Untiy method:
UnityPlayer.UnitySendMessage("Manager""ZoomIn""");

The first argument is a game object object, so you need to bind the script on the player, the second parameter is the method name defined in unity, and the third parameter is the parameter that defines the method (nullable).

You can either change the name of the game object when you define the scene, or you can set it in your code:

void Start () {  this"Manager";  GetData (); }

After running in unity, you'll find a "Manager" of the game scene.

Here's a look at the activity code:

 Packagecom.jacksen.unity2android;ImportCom.unity3d.player.UnityPlayer;ImportAndroid.os.Bundle;ImportAndroid.view.KeyEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.LinearLayout;ImportAndroid.widget.Toast; Public  class mainactivity extends unityplayeractivity { PrivateLinearLayout u3dlayout;PrivateButton zoominbtn, zoomoutbtn;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);  Setcontentview (R.layout.activity_main);  U3dlayout = (linearlayout) Findviewbyid (r.id.u3d_layout);  U3dlayout.addview (Munityplayer);  Munityplayer.requestfocus ();  ZOOMINBTN = (Button) Findviewbyid (R.ID.ZOOM_IN_BTN);  ZOOMOUTBTN = (Button) Findviewbyid (R.ID.ZOOM_OUT_BTN); Zoominbtn.setonclicklistener (NewOnclicklistener () {@Override    Public void OnClick(View v) {Unityplayer.unitysendmessage ("Manager","ZoomIn","");  }  }); Zoomoutbtn.setonclicklistener (NewOnclicklistener () {@Override    Public void OnClick(View v) {Unityplayer.unitysendmessage ("Manager","Zoomout",""); }  }); } PublicStringGetName(FinalString str) {Runonuithread (NewRunnable () {@Override    Public void Run() {Toast.maketext (mainactivity. ThisStr +). Show (); }  });return "I'm a monster, hahaha."; }/** * 3D Call this method to exit 3D * /  Public void makepauseunity() {Runonuithread (NewRunnable () {@Override    Public void Run() {if(Munityplayer! =NULL) {Try{munityplayer.quit (); }Catch(Exception e)     {E.printstacktrace (); }} mainactivity. This. Finish (); }  }); }/** * Key Click event * / @Override  Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {if(keycode = = Keyevent.keycode_back)  {OnDestroy (); }return true; }@Override protected void OnDestroy() {Super. OnDestroy ();//unityplayer.unitysendmessage ("Manager", "Unload", "" ");Munityplayer.quit (); }//Pause Unity @Override protected void OnPause() {Super. OnPause (); Munityplayer.pause (); }//Resume Unity @Override protected void Onresume() {Super. Onresume (); Munityplayer.resume (); }@Override  Public void onbackpressed() {Super. onbackpressed ();//Munityplayer.quit ();  //This.finish ();}}

OK, the operation effect is as follows:

After jumping to mainactivity, the unity scene launches and calls the GetName () method in Android to assign a value to the label on the Monster's head.
Click the Zoom Out button to call unity in the ZoomIn () and Zoomout () methods to control the monster to become larger and smaller.

OK, so the simple interaction between unity and Android is complete.

This blog to the end ~ ~
Thank you for your support! If there is an error, please indicate ~ ~
Thank you ~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android and Unity Interaction Research

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.