[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, I am Qin Yuanpei. Welcome everyone to follow 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". Through the previous study. You already know that by writing plug-ins for unity in Eclipse, we are able to actually communicate with the Android API today. Unfortunately, this approach does not work for all Android APIs, and at some point we need to his new, export the Unity project as an Android project, and then continue to change the game's content in Eclipse. This approach has been mentioned in the article "Unity3d Game Development Unity and Android Interactive call study", but it has not really been studied.

A friend named @shanlover asked me if I could write a unity project to export eclipse articles, so bloggers took the time to study this approach. Thus with this article of today.

First, let's create a simple scenario:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwluexvhbnblaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

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>///definition of the camera's near 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 , as we need to use this name in///Android project, get the main camera object at the same time///</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. This allows us to get an Android project that can be opened 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 number used in this book is 4.X, and the unity version number used by the blogger 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 such a method. With the idea of trying, the blogger directly executes the Android project that was exported by unity. The result program was successfully executed on the phone.


So. Next we'd better calmly analyze this Android project from unity, and we can see the directory structure of the entire project as follows:


In this directory structure, we can see that it is a standard Android project. The Unity-class.jar in Libs is the JAR library file we used in the previous article. In the assets directory, we can see the DLL files that unity relies on. In the Com.android.unity2eclipse package. We will find a class named Unityplayernativeactivity.class, which defines such as the following:

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 think this kind of familiar. Yes, in the previous article "Embedded Unity View in Android View" in the Unity3d game development, we used this class to embed the Unity view in Android view. Just when this class was defined in Unity's Unity-class.jar library, and more precisely in the Unityplayernativeactivity class Com.unity3d.player the package, we noticed that this class was inherited from native Activity, in the previous article the blogger mentioned this class, which is an interface that Android provides to C + + developers.

Other words. The Unity project on the Android platform relies on essentially the nativeactivity interface, only the interface that unity itself uses is encapsulated. And the interface we use here is directly inherited from the parent class. Then, we will have doubts at this moment. From this class to the detailed implementation of the basic function is to initialize the activity, then we can see in the activity what is determined by whom? It is noted that there is a Setcontentview () method here. It passes in the Unityplayer type of the argument as the activity display content. It is believed that from now on, everyone's understanding of the Android interface provided by unity will become clearer.

In order to validate our ideas, next. Let's create a layout file Activity_main. Its code definition is 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 piece of code. We call the two methods ZoomIn, zoomout defined in unity through unitysendmessage. Okay, next. We change 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:versionname= "1.0" and Roid:versioncode= "1" android:installlocation= "preferexternal" > <supports-screens android:smallScreens= "True "Android:normalscreens=" true "android:largescreens=" true "android:xlargescreens=" true "Android:an Ydensity= "true"/> <application android:icon= "@drawable/app_icon" android:label= "@string/app_name" Android Oid:debuggable= "false" > <activity android:label= "@string/app_name" android:screenorientation= "FullSensor" Android:launchmode= "Singletask" android:configchanges= "Mcc|mnc|locale|touchscreen|keyboard|keyboardhidden |navigation|orientation|screenlayout|uimode|screensize|smallestscreensize|fontscale "Android:name=" Com.android.unity2ecplise.MainActivity "> &Lt;intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "an Droid.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 have predicted. 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 custom class. This allows us to use a custom 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 problem, that is, in the configuration file to add such two lines of code, at this time, people are not as taichetaiwu as the blogger feeling it. We execute the program and we find that the interface is changed as we would like to see it. And we can change the size of the cube in the view by two buttons:



watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwluexvhbnblaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

So that we can realize that the Android project was exported from unity. We are able to change it directly to meet our requirements. As for Jinzeng Teacher's method. In the official API documentation did mention the method, but bloggers have been trying for a long time, such a method has failed, do not know is not because unity in the new version number has overcome this problem, so that can directly export the executable Android project.

Finally, a way to spread on the internet. It is said that under project build in Unity, a directory named Stagingarea is generated under the TEMP directory in the project directory . We will import this directory into Eclipse and set it as a library, and then reference it in the new Android project. and overwrite the assets directory in this project with the assets directory in the new project, then we just have to let the main acitivity inherit unityplayeractivity from the Android interface provided by Unity . This way the blogger does not try, but it does produce such a directory at build time. It's just that bloggers think this is a bit of a hassle, since the unity-exported Android project will work directly. Why do we need to use such a complex method, but I think the general idea is this, unityplayeractivity responsible for acivity life cycle maintenance. 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 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 they go very far. A man who lacks patience 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 , the source of this article: http://blog.csdn.net/qinyuanpei/article/details/39717795

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


This article source code download: Unity Project Android Project


[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.