Research on interaction between Android and Unity

Source: Internet
Author: User

Research on interaction between Android and Unity
Research on interaction between Android and Unity

 

Study on Interaction between Android and Unity the origin of interaction between unity and android unity a brief introduction to interaction between unity and android the method of unity calling android the method of android calling untiy

Interaction between unity and android

In the project development process, I encountered such a requirement to display the unity scenario in android. At the beginning, unity was also confused. Later, I found a lot of materials to achieve the desired results. Therefore, record some of your summary here for your reference.

Unity

Unity is a multi-platform integrated game development tool that can develop interactive content such as 3D video games, architectural models, and 3D animations.Cross-platform. After compiling the scenario and program in unity, you can export the versions of Android, ios, windows phone, PC, and other platforms.

For example, list all platforms that unity can export.

Interaction between unity and android

Generally, unity is used as a part of the android program, and a u3d scenario is used as an interface or part of an interface.
In addition, android is developed as part of unity. However, this form of development is rare and unnecessary.

The following is an example to describe the interaction between the two.

First, a game scenario is created in unity. After the game is run, it is shown as follows:

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

How unity calls android

After running the Unity engine, we need Uniy to call the Android method to obtain the name of the monster by calling methods in the java class.
There are four java methods called by unity:

Common method without return value
AndroidJavaObject jo = new AndroidJavaObject(android.content.res.Configuration);jo.Call(setToDefaults);
Common methods with return values
AndroidJavaObject jo = new AndroidJavaObject(java.lang.String, some string);int hash = jo.Call
  
   (hashCode);
  
Static Method without return value
AndroidJavaObject jo = new AndroidJavaObject(android.os.Binder);jo.CallStatic(flushPendingCommands);
Static methods with return values
AndroidJavaObject jo = new AndroidJavaObject(java.lang.String);string valueString = jo.CallStatic
  
   (valueOf, 42.0);
  

We bound some operations to the game object-Operate. cs:

Using UnityEngine; using System. Collections; public class Operate: MonoBehaviour {public Transform target; public UILabel label; public bool flag = true ;////// Define the rotation speed ///Public float RotateSpeed = 45; // Use this for in itializationvoid Start () {// Debug. Log (hello); this. name = Manager; GetData ();}////// Obtain the name by calling the method in android and assign a value to the label ///Void GetData () {AndroidJavaClass jc = new AndroidJavaClass (com. unity3d. player. UnityPlayer); AndroidJavaObject jo = jc. GetStatic (currentActivity); string name = jo. Call
  
   
(GetName, android method called successfully); label. text = name;} // Update is called once per framevoid Update () {// target. rotate (Vector3.up * Time. deltaTime * RotateSpeed);} void OnClick () {Screen. orientation = ScreenOrientation. landscape; if (flag) {target. localScale = new Vector3 (0.5f, 0.5f, 0.5f); flag = false; // label. text = 123456;} else {target. localScale = new Vector3 (0.75f, 0.75f, 0.75f); flag = true; // label. text = 000000 ;}}///
   /// Top down the previous scene ///Void Unload () {Application. loadLevel (1); AndroidJavaClass jc = new AndroidJavaClass (com. unity3d. player. unityPlayer); AndroidJavaObject jo = jc. getStatic (currentActivity); jo. call (makePauseUnity );}///
   /// Zoom in ///Void ZoomIn () {target. localScale = new Vector3 (0.75f, 0.75f, 0.75f );}///
   /// Zoom out ///Void ZoomOut () {target. localScale = new Vector3 (0.5f, 0.5f, 0.5f );}}
  

After the code and scenario are compiled, you can use the unity apk file to run it. However, we need to perform secondary development in eclipse, so we need android projects everywhere.

You can select "Google Android Project" for export ".

For example, if this option is not checked, an apk file is exported.
Before exporting an android project or apk, You need to perform some configuration in "Player Settings:

These configurations are basically consistent with our development settings in eclipse and other tools.
After exporting the android project, the directory structure is shown as follows:

Rotate + rotate + m/rotate/uxL/rotate/a1xLmks8y1vMjrxOO1xElERdbQvLS/yaGjDQo8cD6/rotate "brush: java;">

Before pasting the logic code, let's first introduce how Android calls the unity Method:

Android calls the untiy method:
UnityPlayer.UnitySendMessage(Manager, ZoomIn, );

The first parameter is the Game Object, so you need to bind the script to the Game Object. The second parameter is the method name defined in unity, the third parameter is the parameter that defines the method (which can be null ).

You can change the name of a game object when defining a scenario, or set it in the Code:

void Start () {  this.name = Manager;  GetData (); }

After running in unity, you will find a "Manager" game scenario.

Let's take a look at the activity code:

Package com. jacksen. unity2android; import com. unity3d. player. unityPlayer; import android. OS. bundle; import android. view. keyEvent; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. linearLayout; import android. widget. toast; public class MainActivity extends UnityPlayerActivity {private LinearLayout u3dLayout; private Button zoomInBtn, zoo MOutBtn; @ 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. setOnClickList Ener (new OnClickListener () {@ Override public void onClick (View v) {UnityPlayer. unitySendMessage (Manager, ZoomIn,) ;}}); zoomOutBtn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {UnityPlayer. unitySendMessage (Manager, ZoomOut,) ;}}) ;}public String getName (final String str) {runOnUiThread (new Runnable () {@ Override public void run () {Toast. makeText (MainAc Tietong. this, str, 1000 ). show () ;}}); return I am a monster, hahaha;}/*** call this method to exit 3D */public void makePauseUnity () {runOnUiThread (new Runnable () {@ Override public void run () {if (mUnityPlayer! = Null) {try {mUnityPlayer. quit ();} catch (Exception e) {e. printStackTrace () ;}} MainActivity. this. finish () ;}}) ;}/ *** click the event button */@ Override public boolean onKeyDown (int keyCode, 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 running effect is as follows:

After the jump to MainActivity, the unity scenario is started. Call the getName () method in android to assign values to the label on the monster head.
Click the zoom in and zoom out button to call the ZoomIn () and ZoomOut () methods in Unity respectively, and control the monsters to become larger and smaller.

OK. Now the simple interaction between unity and android is complete.

Related Article

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.