[Unity3d] Unity3d game development from Unity3d to eclipse

Source: Internet
Author: User

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/39717795

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------


Hello friends Everyone, I am Qin Yuanpei, welcome to pay attention to my blog, my blog address is Blog.csdn.net/qinyuanpei. First of all, I wish you a pleasant 11 holiday. Today, Bo will send the last article of the Unity-android series "Unity3d game development from Unity3d to eclipse". With the previous learning, you already know that by writing plugins for unity in eclipse, we can communicate with the Android API in unity. Unfortunately, this approach doesn't work for all Android APIs, and at some point we need his new to export the Unity project as an Android project and then continue to modify the game's content in Eclipse. This approach has been mentioned in the Unity3d game development Unity and Android Interactive call study, but has not really been studied. A friend named @shanlover asked me if I could write a unity project to export eclipse articles, so the blogger took the time to study this approach, thus having this article today. First, let's create a simple scenario:


Well, once the scene is created, we can write a script CubeScripts.cs to control the cube in the scene:

Using unityengine;using System.collections;public class Cubescripts:monobehaviour {//<summary>///define rotational speed/// Lt;/summary>public float rotatespeed=45;///<summary>///defines the camera's nearest distance//</summary>private float mNear=    2.5F; <summary>///camera Current distance//</summary>private float mdistance=5f;///<summary>///define the maximum distance of the camera//< /summary>private float mfar=7.5f;///<summary>///camera zoom rate///</summary>private float mzoomrate=0.5f;/ <summary>///main camera///</summary>private Transform mcamera;///<summary>///in the start () method we set the name of the game body , because we need to use this name in///Android project, and get the main camera object///</summary>void Start () {this.name= "main Cube"; mcamera= Camera.main.transform;} <summary>///in the update () method we let cube rotate at a certain speed///</summary>void Update () {transform. Rotate (vector3.up * time.deltatime * rotatespeed);} <summary>///defines a magnified method for external calls//</summary>public void ZoomIn () {mdistance-=mzoomrate;mdistance= Mathf.clamp (MdistanCE,MNEAR,MFAR); Mcamera.position=mcamera.rotation * New Vector3 (0,0,-mdistance) +transform.position;} <summary>///defines a narrowing method for external calls//</summary>public void Zoomout () {mdistance+=mzoomrate;mdistance= Mathf.clamp (MDISTANCE,MNEAR,MFAR); Mcamera.position=mcamera.rotation * New Vector3 (0,0,-mdistance) + Transform.position;}}
This script is very simple, there is nothing to say, here we define two methods ZoomIn and Zoomout, these two methods we will provide to Android to invoke. We bind this script to the object of the main cube. Next, we build the project, where we set the project's PackageName to Com.android.unity2eclipse and export it as an Android project:


So we have an Android project that we can open in eclipse. But how do we use this Android project? In Jinzeng's "Unity3d Mobile game development", the Android project of Unity Export was used as a library, and then a new Android project was used to invoke the library. The unity version used in this book is 4.X, and the unity version used by bloggers is 4.5.1. The original blogger was based on this idea to write the Android program, but after countless failures, bloggers began to doubt the correctness of this method. With the idea of trying, the blogger ran the Android project, which was exported by unity, and the program successfully ran on the phone.


So, let's take a cool look at this Android project that was exported from unity, and we can see the directory structure for the entire project:


In this directory structure, we can see that it is a standard Android project, and the Unity-class.jar in Libs is the JAR library file we used in the previous article. In the Assets folder we can see the DLL files that unity depends on. In Com.android.unity2eclipse This package, we will find a class named Unityplayernativeactivity.class, which is defined as follows:

Package Com.android.unity2ecplise;import Com.unity3d.player.*;import Android.app.nativeactivity;import Android.content.res.configuration;import Android.graphics.pixelformat;import Android.os.Bundle;import Android.view.keyevent;import Android.view.motionevent;import Android.view.window;import Android.view.windowmanager;public class Unityplayernativeactivity extends nativeactivity{protected UnityPlayer munityplayer;//don ' t change the name of this variable; Referenced from native code//Setup activity layout@override protected void OnCreate (Bundle savedinstancestate) {REQUESTW Indowfeature (Window.feature_no_title); super.oncreate (savedinstancestate); GetWindow (). Takesurface (NULL); SetTheme (Android. R.style.theme_notitlebar_fullscreen); GetWindow (). SetFormat (pixelformat.rgb_565); munityplayer = new UnityPlayer ( This), if (Munityplayer.getsettings (). Getboolean ("Hide_status_bar", True)) GetWindow (). SetFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN, Windowmanager.layoutparaMs. Flag_fullscreen); Setcontentview (Munityplayer); Munityplayer.requestfocus ();} Quit unity@override protected void OnDestroy () {munityplayer.quit (); Super.ondestroy ();} Pause unity@override protected void OnPause () {super.onpause (); Munityplayer.pause ();} Resume unity@override protected void Onresume () {super.onresume (); Munityplayer.resume ();} This ensures the layout is correct @Override public void onconfigurationchanged (Configuration newconfig) {Super.on Configurationchanged (Newconfig); munityplayer.configurationchanged (newconfig);} Notify Unity of the focus change. @Override public void Onwindowfocuschanged (Boolean hasfocus) { Super.onwindowfocuschanged (Hasfocus); munityplayer.windowfocuschanged (Hasfocus);} For some reason the multiple keyevent type are not supported by the NDK.//force event injection by overriding Dispatchk Eyevent (). @Override public boolean dispatchkeyevent (KeyEvent event) {if (event.getaction () = = Keyevent.action_multiple ) return Munityplayer.injectevent (event); return super.dispatchkeyevent (event);} Pass any events not handled by (unfocused) views straight to Unityplayer@override public boolean onKeyUp (int keycode, K Eyevent event) {return munityplayer.injectevent (event);} @Override public boolean onKeyDown (int keycode, keyevent event) {return munityplayer.injectevent (event);} @Override public boolean ontouchevent (Motionevent event) {return munityplayer.injectevent (event);} /*api12*/public boolean ongenericmotionevent (Motionevent event) {return munityplayer.injectevent (event);}}
I believe most people who read my blog will find this kind of familiar, right, in the previous "Unity3d game development in Android view embedded in Unity View" in this article, we use this class to achieve in Android view embedded Unity View, It was only then that the class was defined in Unity's Unity-class.jar library, and more precisely in the Unityplayernativeactivity class under the Com.unity3d.player package, and we noticed that this class was inherited from Nativea Ctivity, in the previous article, has mentioned this class, which is an interface that Android provides to C + + developers. In other words, the Unity project relies on the Nativeactivity interface on the Android platform, but the interface that Unity uses itself is encapsulated, and the interface we use here is directly inherited from the parent class. So, we have a question at this moment, from this class from the specific implementation of the main function is to initialize the activity, then we in the activity can see what is decided by whom? It is noted that there is a Setcontentview () method that passes the parameters of the Unityplayer type as content displayed by the activity. It is believed that from now on, you will become more and more aware of the Android interface provided by Unity. To validate our ideas, let's create a layout file, Activity_main, whose code is defined as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <button android:id=" @+id/btnzoomin "android:layout_width=" Match_parent "Android    oid:layout_height= "Wrap_content" android:layout_alignparenttop= "true" android:text= "@string/zoomin"/> <linearlayout android:id= "@+id/unityview" android:layout_width= "Match_parent" android:layou          t_height= "Match_parent" android:layout_above= "@+id/btnzoomout" android:layout_below= "@+id/BtnZoomIn"        android:orientation= "vertical" > </LinearLayout> <button android:id= "@+id/btnzoomout" Android:layout_width= "Match_parent" android:layout_height= "Wrap_content" Android:layout_alignparentbotto M= "true"        android:text= "@string/zoomout"/></relativelayout> 
Next, we create the corresponding Java class file Mainactivity.class:

Package Com.android.unity2ecplise;import Com.android.unity2ecplise.r;import Com.unity3d.player.unityplayer;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import android.widget.linearlayout;/* The mainactivity we have defined here inherits from the Unityplayernativeactivity*/public class in the Unity Export project Mainactivity extends Unityplayernativeactivity {private Button btnzoomin,btnzoomout; @Override protected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Gets the parent control that displays the Unity View LinearLayout mparent= (linearlayout) Findviewbyid (R.id.unityview);//Get Unity View View mview= Munityplayer.getview ();//Add Unity view to Android View Mparent.addview (MView);//Zoom in btnzoomin= (Button) Findviewbyid ( R.id.btnzoomin); Btnzoomin.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) { Unityplayer.unitysendmessage ("Main Cube", "ZoomIn", "");}}); /reduced btnzoomout= (Button) Findviewbyid (r.id.btnzoomout); Btnzoomout.setOnclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {unityplayer.unitysendmessage ("Main Cube "," Zoomout "," ");}});}}
In this code, we call the two methods ZoomIn, zoomout defined in unity through unitysendmessage. Well, next, we modify the configuration file so that the main activity corresponds to the Mainactivity class, open
Androidmanifest.xml file:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.android.unity2ecplise "Android:theme=" @android: Style/theme.notitlebar "Android:versionna Me= "1.0" android:versioncode= "1" android:installlocation= "preferexternal" > <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/ap P_name "android:debuggable=" false "> <activity android:label=" @string/app_name "android:screenorient ation= "Fullsensor" android:launchmode= "Singletask" android:configchanges= "Mcc|mnc|locale|touchscreen|keybo Ard|keyboardhidden|navigation|orientation|screenlayout|uimode|screensize|smallestscreensize|fontscale "Android:   Name= "Com.android.unity2ecplise.MainActivity" >   <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category Android:nam E= "Android.intent.category.LAUNCHER"/> </intent-filter> <meta-data android:name= "Unityplayer. Unityactivity "android:value=" true "/> <meta-data android:name=" Unityplayer. Forwardnativeeventstodalvik "android:value=" true "/> </activity> </application> <uses-sdk android: minsdkversion= "9" android:targetsdkversion= "/>" <uses-feature android:glesversion= "0x00020000"/></ Manifest>
As we guessed, the Name property of the Acivity node corresponds to com.android.unity2ecplise.UnityPlayerNativeActivity. This shows that prior to this, Android was using this class as the main acivity. Now let's change it to our own defined class so that we can use our own defined layout. At the same time you will notice the following two lines:

      <meta-data android:name= "Unityplayer. Unityactivity "android:value=" true "/>      <meta-data android:name=" Unityplayer. Forwardnativeeventstodalvik "android:value=" true "/>
Before we were talking about the unity view embedded in the Android view when the Android view was not able to focus on the issue, that is, in the configuration file with such two lines of code, at this time, people are not as taichetaiwu as the blogger feeling it. We run the program and we see that the interface is changed as we want it to be, and we can change the size of the cube in the view by two buttons:





This allows us to realize that the Android project is exported from unity and that we can modify it directly to meet our requirements. As for the Jinzeng teacher's approach, this is true in the official API documentation, but bloggers have been trying for a long time and this method has failed, not knowing that unity has solved this problem in the new version so that it can directly export the running Android project.

In the end, a way of circulating on the internet, it is said that under the project build in Unity, a folder named Stagingarea is generated under the Temp folder in the project directory , which we import into Eclipse and set it as a library, then reference the library in the new Android project and overwrite the assets folder in the project with the assets folder in the new project. Then we just have to let the master acitivity inherit the unityplayeractivity from the Android interface provided by Unity . This method blogger did not try, but in the build when it does produce such a folder, but bloggers think this is not a bit of trouble ah, since the unity exported Android project directly can be used, we need to use this complex method, But I think the general idea is that unityplayeractivity is responsible for the maintenance of the acivity life cycle, Unityplayer is responsible for rendering the content in the unity scene, And the resources we use in unity are handled internally by Unity's engine, and with this in common, the interaction between unity and Android is basically no problem. Well, thank you for your attention to my blog, today's content is this, I hope you like.


Daily Proverbs: Some roads look very close, but go down very far, the lack of patience of the people will never go to the end. Life, half is reality, half is dream. --gu Cheng




--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/39717795

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------




[Unity3d] Unity3d game development from Unity3d to eclipse

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.