[Unity3D] research on interaction between Unity and Android in Unity3D game development, unity3dandroid
Dear friends, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei. In the previous article, we studied Unity3D gesture operations on the Android platform and implemented functions such as gesture rotation and scaling. Today, we will continue to study the extended content of Unity on the Android platform. As we all know, Unity3D is a powerful cross-platform game engine. Like most friends who like Unity, bloggers are deeply shocked after experiencing the powerful cross-platform capabilities of Unity, imagine if we wanted to develop a game in the past, we needed to have a good understanding of DX, OpenGL, and other graphics libraries. Due to the strict performance requirements of the game, top commercial game engines such as Unreal and CryEngine are usually developed using the underlying Language C/C ++, which makes many developers discouraged. At this moment, thanks to the powerful cross-platform capabilities of Unity3D, bloggers can write games in their favorite C # language, which undoubtedly means that mingbo is the same as thousands of developers who use Unity, we are in an era when commercial engines gradually mature. as developers, we are happy.
I remember "Yao zhuangxian, father of xianjian," When I participated in the Unity Asia regional competition as a judge, I felt: "I was also obsessed with constantly researching game development and starting from various games and gadgets, and constantly optimize and improve previous works, accumulating experience and skills. At that time, there was no commercial engine available, and you needed to build the underlying engine for yourself. Nowadays, young people are happy to learn and use the engine that Unity exposes to the public. They can focus more on the creation of game works, we should take such an environment into account ". Therefore, compared with the game industry's predecessors who used QBasic to write game works such as "Legend of the fairy sword", our generation is undoubtedly much happier, but our generation has little burden. Today's era is a diversified era. whether in the field of application development or game development, the diversified target user platforms have become a problem we have to deal. Taking mobile Phone platforms in China as an example, there are three mainstream mobile Phone platforms: IOS, Android, and Window Phone. Although theoretically, we can develop apps on IOS and Android without writing a line of Object-C or Java code, however, if we need to interact with some interfaces of the platform, we have to consider the connection between Unity and these platforms. For the most common example, we all know that a pay-as-you-go method is popular on mobile platforms, but Unity does not provide the corresponding APIs for us, because of the unique legitimacy of the Apple App Store on the IOS platform, we need to use the SDK officially provided by Apple to achieve in-app payment on the platform, while Apple officially promotes Object-C, therefore, we will inevitably deal with Object-C. Similarly, on the Android platform, because of the diversity of Android devices and app stores caused by the open-source Android, when we choose to shelve our apps, it also faces problems dealing with Java or C ++ (JNI. So today, we are going to study the interaction between Unity and other platforms. As the blogger has only one Android mobile phone that has been used for a long time, so let's take the Android platform as an example to discuss the interaction between Unity and Android!
There are two ways to interact between Unity and Android:
1. Unity calls the plugin compiled for the Android platform
2. Export the Unity project as an Android project, and then write the Android Program
These two methods have their own advantages and disadvantages in actual application. Let's explain the first method today, and the second method, the blogger will share with you later. First, let's talk about the principle of the first method. First, we use Eclipse to compile a Java library file (. jar). In this library file, we will encapsulate a series of methods to provide interfaces for Unity, after exporting the library file, we can place it in a specific directory (Plugins/Android). Then we can use the APIS provided by Unity to call these methods. Now let's take a look at the specific process. First, create an Android project and set it as a library. Here, set the package name to com. android. android2unity: this package name is very important. We will use this package name in Unity. Next we will write code in MainActivity. java, which will be used as a class for encapsulating Android APIs. Before writing the code, let's do this in D: \ Program Files \ Unity \ Editor \ Data \ PlaybackEngines \ androidplayer \ release \ bin \ classes. jar (on different computers, this location may be different and you can add it according to your own path.) This library is added to our project,
This library is a library provided by Unity for Android. It mainly provides Player that supports this platform. You can view its class space on your own. Now, let's write a script like this:
Package com. android. android2unity; import android. app. alertDialog; import android. content. context; import android. content. intent; import android. OS. bundle; import android. OS. vibrator; import android. widget. toast;/* introduce the Unity package */import com. unity3d. player. unityPlayerActivity; import com. unity3d. player. unityPlayer;/* If Activity needs to be connected to Unity, You can inherit UnityPlayerActivity to implement * // * We need to override the relevant methods of Activity. In this section of code, we only need to call android Oid API */public class MainActivity extends UnityPlayerActivity {// current Context private Context mContext = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // The initialization context mContext = this;}/* defines a method to call the Unity method, which is implemented based on UnitySendMessage. Because the current Activity does not use * // * Android layout file, we cannot use Android events to call this method. We * // * use the Unity call method, although this seems to be far-fetched, we know how to call * // * the method defined in Unity */public void InvokeUnity (String mStr) {UnityPlayer in Android. unitySendMessage ("Vabille", "SetCameraColor", "");}/* defines a method to open an Activity, we will call this method in Unity */public void StartWebView (String mUrl) {// create an Intent to open a new Activity Intent intent = new Intent (mContext, WebActivity. class); // pass in a URLintent. putExtra ("URL", mUrl); // open Activity this. startActivity (intent);}/* defines a display dialog box method. We will call this method in Unity */public void ShowDialog (final String mTitle, final String mContent) {/* execute related methods under the UI thread */runOnUiThread (new Runnable () {@ Overridepublic void run () {// create BuilderAlertDialog. builder mBuilder = new AlertDialog. builder (MainActivity. this); // create dialog box mBuilder. setTitle (mTitle ). setMessage (mContent ). setPositiveButton ("OK", null); // display the mBuilder dialog box. show () ;}}) ;}/ * defines a method for device vibration. We will call this method in Unity */public void SetVibrator (long mTime) {Vibrator mVibrator = (Vibrator) getSystemService (VIBRATOR_SERVICE); mVibrator. vibrate (mTime);}/* defines a method for device vibration. We will call this method in Unity */public void ShowToast (String mContent) {Toast. makeText (mContext, mContent, Toast. LENGTH_LONG );}}
In this Code, we let the MainActivity class inherit from the UnityPlayerActivity provided by Unity, so that we can use some methods provided by Unity in Android. In this Code, five methods are defined, namely, the ShowDialog () method for displaying the dialog box, the ShowToast () method for displaying the Toast, and StartWebView () method for opening an Activity () method, the SetVibrator () method used to vibrate the device, and the InvokeUnity () method used to call the methods defined in Unity. The ShowDialog () method must be run in the UI thread. Here, we do not need to set a layout file for the current Activity, so we do not use the setContentView () method.
Next, we will create a WebActivity class that inherits from the Activity. We hope to load a webpage on this page. The webpage address can be specified through Unity. First, let's look at the layout file avtivity_web.xml, it is a simple linear layout with only one WebView component inside it for displaying webpages:
<?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:orientation="vertical" > <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout>
Correspondingly, it corresponds to the WebActivity class. The StartWebView () method defined in the MainActivity class points to this Acitivity:
Package com. android. android2unity; import android. app. activity; import android. OS. bundle; import android. webkit. webView; public class WebActivity extends Activity {// webpage Group Component private WebView mWebView; protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // sets the current layout setContentView (R. layout. activity_web); // obtain WebView mWebView = (WebView) findViewById (R. id. webView); // obtain the URL String mUrl = this. getIntent (). getStringExtra ("URL"); // load the webpage mWebView. loadUrl (mUrl );}}
It makes it very clear that the forward parameter URL is read from MainActivity, which is a webpage address through which we open a webpage. Finally, let's take a look at the configuration file AndroidManifest. xml of the project. This is a very important file. here we need to register WebActivity and assign corresponding permissions to the application:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.android2unity" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.android.android2unity.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".WebActivity"/> </application> </manifest>
Now, we have basically finished writing the Android plug-in. The last thing we need to do is to output it as a Jar library so that we can use it in Unity, note that all Java classes and configuration file classes (such as attributes, la S, and values) generated by Android must be compiled, previously, the blogger did not understand the compilation of the Jar library. As a result, he paid a lot of twists and turns on both Java and Unity. If you are familiar with Java, you must use commands to output library files. However, the blogger is a newbie and is not familiar with Java commands, therefore, the blogger uses the file-> export to export the Jar file. We need to select the src directory and R. java file. If there is a third-party library, you also need to select the libs Folder:
In this way, we can directly output the Jar library file we need. In this way, we have completed the task of compiling the Unity plug-in Android. Next, let's get into the sphere of Unity, haha!
In Unity, we continue to use the project in our previous article. We continue to use this pretty girl in FF (forgive me for not knowing her name)
The following describes how to organize the directory of the Android plug-in based on this structure:
---------- Assets
---- Plugins
----- Android
----- Bin (stores exported Jar files)
----- Libs (stores third-party libraries)
----- Res (resource folder, which can be directly copied to the Android Project)
----- AndroidManifest. xml (configuration file, which can be directly copied to the Android Project)
The final effect should be as follows:
Now let's write the C # script AndroidAPI. cs.
Using UnityEngine; using System. collections; public class AndroidAPI: MonoBehaviour {void Start () {// set the name of the current game body. In Android, we will use this name. name = "Vabille" ;}// define a method to change the Camera background color. In Android, we will call this method void SetCameraColor () {// set the Camera background color Camera. main. backgroundColor = new Color (1.0F, 0.5F, 0.5F);} void OnGUI () {// if (GUILayout. button ("Call Android API display dialog box", GUILayout. height (45) {// obtain the Android Java interface AndroidJavaClass Jc = new AndroidJavaClass ("com. unity3d. player. unityPlayer "); AndroidJavaObject jo = jc. getStatic <AndroidJavaObject> ("currentActivity"); // constructor string [] mObject = new string [2]; mObject [0] = "Unity3D "; mObject [1] = "Unity3D successfully called Android API"; // call method jo. call ("ShowDialog", mObject);} // open Activityif (GUILayout. button ("Open Activity in Android API call", GUILayout. height (45) {// obtain the Android Java interface AndroidJavaClass jc = new AndroidJava Class ("com. unity3d. player. unityPlayer "); AndroidJavaObject jo = jc. getStatic <AndroidJavaObject> ("currentActivity"); // open the blog jo of the blogger. call ("StartWebView", "http://blog.csdn.net/qinyuanpei");} // Call Toastif (GUILayout. button ("Call Toast in Android API", GUILayout. height (45) {// obtain the Android Java interface AndroidJavaClass jc = new AndroidJavaClass ("com. unity3d. player. unityPlayer "); AndroidJavaObject jo = jc. getStatic <AndroidJavaOb Ject> ("currentActivity"); // open the blog jo. Call ("ShowToast", "Writing Android plug-ins for Unity3D is a tough task! ");} // Call Toastif (GUILayout. button ("Call the vibration method in Android API", GUILayout. height (45) {// obtain the Android Java interface AndroidJavaClass jc = new AndroidJavaClass ("com. unity3d. player. unityPlayer "); AndroidJavaObject jo = jc. getStatic <AndroidJavaObject> ("currentActivity"); // open the blog jo of the blogger. call ("SetVibrator", 40);} // Call Toastif (GUILayout. button ("calling methods in Unity through SendMessage", GUILayout. height (45) {// obtain the Android Java interface AndroidJavaClass jc = new AndroidJavaClass ("com. unity3d. player. unityPlayer "); AndroidJavaObject jo = jc. getStatic <AndroidJavaObject> ("currentActivity"); // open the blog jo of the blogger. call ("InvokeUnity ","");}}}
The methods here are called methods defined in Android, mainly by using the Call () method of AndroidJavaObject. This method has two parameters. The first parameter is a variable of the encoding type, is the name of the method to be called. The second parameter is of the object [] type and is the parameter of the method to be called. Okay. Let's take a look at the running effect on your phone!
This is the result of today, but everyone knows my habits. Every time I can't solve the problem in my article, I will talk about it in my blog to help you solve it, the problem today is that the ShowToast () method and SetVibrator () method have never been called. The bloggers suspect that Unity provides limited Java interface capabilities and can only access some Android interfaces, I don't know what you think. If you know, I hope you can tell me.
Finally, we have defined a SetCameraColor () method in C #. This is a method for changing the camera background. We use InvokeUnity () in Android () method to access this method. Because Android layout elements are not used in the first page, we cannot use Android events. We still use the method called in Unity, however, Android can call the Unity method, and the specific implementation is implemented by SendMessage, I personally think this is a kind of delegation. We noticed that the screen color turned red, indicating that this method was called. Well, today's content is like this. I feel so tired after writing this article!
Daily Rumor: Loneliness is the companion of life, and loneliness is the frequent visitor of life. Life is a practice. practice must be patient, be able to endure loneliness, and be Regretless.
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/39348677
I used Unity3D to prepare my own game project. How can I import it to an android mobile phone? Do I still need to call the android SDK?
For u3d development, you only need to use C # scripts or javascript. To release android, you must first download and install the android SDK and configure it, and then select android in u3d build setting, during the generation process, you are required to enter the installation path of the android SDK and fill it in.
Unity3d interaction with HTML
Generally, SendMessage (…) is used to call the public method of unity3d activex externally (......), Use ExternalCall (…) to call external methods from the unity3d plug-in (......), You can check the usage in the help manual, or click here docs.unity3d.com/...n.html