[Unity3D] Unity3D game development from Unity3D to Eclipse, unity3declipse

Source: Internet
Author: User

[Unity3D] Unity3D game development from Unity3D to Eclipse, unity3declipse

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.

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

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Hello everyone, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei. First of all, I wish you a pleasant eleven holiday. Today, the blogger will send you the last article "Unity3D game development from Unity3D to Eclipse" in the Unity-Android series. Through the previous study, we know that by compiling a plug-in for Unity in Eclipse, we can implement communication between Unity and Android APIs. Unfortunately, this method does not work for all Android APIs. In some cases, we need to export the Unity project as an Android project, then, modify the game content in Eclipse. This method has been mentioned in the article "Study on Interaction between Unity and Android in Unity3D game development", but it has not been studied. A friend called @ SHANlover asked me if I could write an article about exporting Eclipse from the Unity project. Therefore, the blogger took the time to study this method, so we can see this article today. First, let's create a simple scenario:


After creating the scenario, we can directly write a script CubeScripts. cs to control the Cube in the scenario:

Using UnityEngine; using System. collections; public class CubeScripts: MonoBehaviour {// <summary> // define the rotation speed /// </summary> public float RotateSpeed = 45; /// <summary> /// defines the nearest distance of the camera /// </summary> private float mNear = 2.5F; /// <summary> /// Current Camera distance /// </summary> private float mDistance = 5F; /// <summary> /// define the maximum distance of the camera /// </summary> private float mFar = 7.5F; /// <summary> /// the camera's Zoom rate /// </summary> private float mZoomRate = 0.5F; /// <summary> /// main camera /// </summary> private Transform mCamera; /// <summary> // At Start () the method sets the name of the game body, because we need this name in the // Android project, and get the main camera object // </summary> void Start () {this. name = "Main Cube"; mCamera = Camera. main. transform;} // <summary> // In the Update () method, let the Cube rotate at a certain speed. // </summary> void Update () {transform. rotate (Vector3.up * Time. deltaTime * RotateSpeed);} // <summary> // defines a 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 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 and there is nothing to say. Here we define two methods ZoomIn and ZoomOut, which we will provide for Android to call. We will bind this script to the Main Cube object. Next, we will Build the project. Here we will set the PackageName of the project to com. android. unity2eclipse, and then export it as an Android project:


Then, we will get an Android project that can be opened in Eclipse. But how can we use this Android project? In the book Unity3D mobile game development by Mr. Jin Zeng XI, the Android project exported by Unity is used as a library, and then a new Android project is used to call this library. The version of Unity used in this book is 4.X, and the version of Unity used by bloggers is 4.5.1. At first, the blogger compiled the Android program based on this idea, but after countless failures, the blogger began to doubt the correctness of this method. With the idea of trying, the blogger directly runs the Android project exported by Unity, and the result program runs successfully on the mobile phone.


Then, let's analyze the Android project exported from Unity calmly. We can see that the directory structure of the entire project is 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 folder, we can see the dll file on which Unity depends. In the Package com. android. unity2eclipse, 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){requestWindowFeature(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 will be correct.@Override public void onConfigurationChanged(Configuration newConfig){super.onConfigurationChanged(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 is not supported by the ndk.// Force event injection by overriding dispatchKeyEvent().@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, KeyEvent 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 have read my blog will find this class a little familiar. It's good. In the previous article "Unity3D game development embedded in the Unity view in the Android View, we use this class to implement the embedded Unity view in the Android view, but at that time this class was defined in the Unity unity-class.jar library, and more precisely in the com. unity3d. the UnityPlayerNativeActivity class under the player package. We noticed that this class inherits from NativeActivity. in the previous article, the blogger mentioned this class, it is an interface provided by Android to C/C ++ developers. In other words, the Unity project relies on the NativeActivity interface internally on the Android platform, except that the interfaces used by Unity are encapsulated, and the interfaces used here are directly inherited from the parent class. At this moment, we will have questions. The main function of this class is to initialize the Activity, so we can see in the Activity who decides what to decide? You have noticed that there is a SetContentView () method, which passes in a parameter of the UnityPlayer type as the content displayed by the Activity. I believe that from now on, you will have a clearer understanding of the Android interfaces provided by Unity. To verify our ideas, we will 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:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:id="@+id/BtnZoomIn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:text="@string/ZoomIn" />    <LinearLayout          android:id="@+id/UnityView"          android:layout_width="match_parent"          android:layout_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_alignParentBottom="true"        android:text="@string/ZoomOut" /></RelativeLayout>
Next, we will 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 defined here inherits the UnityPlayerNativeActivity */public class MainActivity extends UnityPlayerNativeActivity {private Button BtnZoomIn, BtnZoomOut; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the parent control LinearLayout mParent = (LinearLayout) findViewById (R. id. unityView); // obtain the Unity View. mView = mUnityPlayer. getView (); // Add the Unity View to the mParent In the Android view. addView (mView); // enlarge BtnZoomIn = (Button) findViewById (R. id. btnZoomIn); BtnZoomIn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {UnityPlayer. unitySendMessage ("Main Cube", "ZoomIn", "") ;}}); // reduce 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 and ZoomOut defined in Unity through UnitySendMessage. Now, let's modify the configuration file so that the main Activity corresponds to the MainActivity class.
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" 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/app_name"       android: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">      <intent-filter>        <action android:name="android.intent.action.MAIN" />        <category android:name="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="17" />  <uses-feature android:glEsVersion="0x00020000" /></manifest>
As we have guessed, the name attribute of the acivity node corresponds to com. android. unity2ecplise. UnityPlayerNativeActivity. This indicates that Android uses this class as the main Acivity. Now we can 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" />
Previously, when we talked about how to embed the Unity view into the Android view, we encountered the problem that the Android view could not get the focus. At that time, we added these two lines of code to the configuration file. At this moment, do you feel like a blogger. When we run the program, we will find that the interface is changed as we expected, and we can use two buttons to change the cube size in the View:





In this way, we can realize that the Android project exported from Unity can be directly modified to meet our requirements. As for this method, I did mention it in the official API documentation, but the blogger tried it for a long time and it failed, I don't know if it is because Unity has solved this problem in the new version, so that you can directly export runnable Android projects.

Finally, there is a method circulating on the network. It is said that in Unity, the Project Build will generate a folder named StagingArea under the Temp folder under the project directory, we will import this folder into Eclipse and set it as a library, and then reference this library in the newly created Android project, and overwrite the assets folder in this project to the assets folder in the new project. Then, we only need to let the main Acitivity inherit the UnityPlayerActivity In the Android interface provided by Unity. This method is not tried by the blogger, but such a folder is indeed generated during Build, but the blogger thinks it is a little troublesome, since the Android project exported by Unity can be used directly, why do we need to use this complicated method? However, I think the general idea is that UnityPlayerActivity is responsible for Acivity lifecycle maintenance, unityPlayer is responsible for rendering the content in the Unity scenario, and the resources we use in Unity are processed internally by the Unity engine, interaction between Unity and Android is basically okay. Well, thank you for your attention to my blog. Today's content is like this. I hope you will like it.


Daily proverbs: some roads look very close, but they are far behind. People who lack patience will never go. Half of life is reality and half is dream. -- Gu cheng




Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.

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

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Download the source code of this article: Android project of the Unity Project



Unity3d development of 3D Game android game touch screen setting programming is also carried out in unity3d or in eclipse

For unity3d code writing, only the built-in mono can be used to view android logs using eclipse;
// Obtain multi-touch data through Input. touches,

Void Update ()
{
Foreach (Touch touch in Input. touches ){
String action = "";
Switch (touch. phase ){
Case TouchPhase. Began:
Action = "start ";
Break;
Case TouchPhase. Moved:
Action = "mobile ";
Break;
Case TouchPhase. Stationary:
Action = "Stay ";
Break;
Case TouchPhase. Ended:
Case TouchPhase. Canceled:
Action = "end ";
Break;
}
Debug. Log (string. Format ("fingerId: {0}, action: {1}, position: {2}", touch. fingerId, action, touch. position ));
}
}

The Unity3d game engine's question can be solved only by writing scripts?

You also need an artist design. You can think that unity3d is a combination of a 3d scene editor and a script interpreter ..
Yes
No, xml will automatically generate


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.