Using the Android SDK in Unity

Source: Internet
Author: User
Tags message queue

If you want to know what love is, where we come from, the meaning of life, the origin of the universe, then please do not read this article.

This is only a boring article, unless you are a tortured ape, otherwise please skip.

Make Java code a Unity plugin

Download the Android SDK, configure the path in unity, and make sure unity can export the APK correctly; Download the JDK and configure the environment variables to ensure that Eclipse opens properly. In addition you need to know to use Eclipse's logcat to view debug log.

1. Open Eclipse, build an Android empty project, note the Package Name column, the name written here is added to the project manifest, only affects the packages that are generated automatically in Gen, because the Android project only For a plug-in project, it is best to differentiate yourself from your own code package name and application package name. Set the minimum SDK, Target SDK version, and click Next.

2. Cancel icon, Activity, mark as Library project, create project directory, click Finish.

3. Before proceeding, explain the structure of the Android project:

SRC: Source code directory, Java code is according to the package name partition directory, root directory is src;

Gen: A directory of automatically generated code, such as a R.java file (this class defines a unique ID for each resource);

Assets: A directory where any other resources can be stored;

Bin: the generated binaries directory;

Libs: The other package file that contains the reference;

Res: Project Standard resource Directory, icons, strings, etc.

Androidmanifest.xml: Configuration Checklist.

All right, that's all you need to know.

4. Open the Unity installation directory and copy the Editor\data\playbackengines\androidplayer\release\bin\classes.jar into the Libs of the Android project, this jar package is only for auxiliary Eclipse code checks and hints, not for final export.

5. Start the code up. Right-click src to create the Java class Unityplugintest.java. Click Finish.

6. Write something useful. For example, the ability to display a small hint of an Android UI style.

 PackageUnityplugin;ImportAndroid.widget.Toast;ImportCom.unity3d.player.UnityPlayer; Public classunityplugintest{ Public Static voidShowtoast (FinalString content,Final BooleanIslong) {UnityPlayer.currentActivity.runOnUiThread (NewRunnable () {@Override Public voidrun () {toast.maketext (unityplayer.currentactivity, content, Islong?Toast.LENGTH_LONG:Toast.LENGTH_SHORT). Show ();    }        }); }}

Note that your project should not contain any errors, otherwise please check if Classes.jar has been successfully referenced.

There is a need to explain this code. First of all, this method is static type. Next we almost put all the code that we need to interact with Unity to be static. No, it is willful. Then notice that in this method we call the UnityPlayer.currentActivity.runOnUiThread method, and the parameter is a Runnable object. Many of the code related to the Android UI must be written in the UI thread, which is similar to the Windows message queue, and things have to be done one thing at a to not mess up. Finally you need to know the keyword final of the function parameter, which allows this parameter to travel through time--oh no, it's going through the Runnable run (if you know that C # delegate can refer to an external variable, you should be familiar with it, just the markup shown here is final).

7. Open Unity, create a new empty Unity project, and switch the target platform to Android. The directory structure that was created.

8. Switch to Eclipse, right click on the Project menu, select "Export ...", export type Select Jar file, click Next, export content select only Bin/classes directory. Export path Select the Libs directory in the Unity project just now. Other options look at the picture. then click Finish.

9. The task on eclipse is now complete. Switch to Unity, add script AndroidBehaviour.cs to the androidscripts directory, and the code is as follows:

     Public Abstract classAndroidbehaviour<t>: MonobehaviourwhereT:androidbehaviour<t>    {        protected Abstract stringJavaclassname {Get; } Private StaticT _instance; protected StaticT instance {Get{return_instance;} }        protectedAndroidbehaviour () {_instance = This  asT;} protected voidCallstatic (stringMethodName,params Object[] args) {            using(Androidjavaclass AJC =NewAndroidjavaclass (Javaclassname)) {AJC.            Callstatic (MethodName, args); }        }        protectedReturnType callstatic<returntype> (stringMethodName,params Object[] args) {            using(Androidjavaclass AJC =NewAndroidjavaclass (Javaclassname)) {                returnAjc. Callstatic<returntype>(MethodName, args); }        }        protectedReturnType getstatic<returntype> (stringfieldName) {            using(Androidjavaclass AJC =NewAndroidjavaclass (Javaclassname)) {                returnAjc. Getstatic<returntype>(FieldName); }        }    }

We will use this class to interact with Java code in the future, and we can invoke static methods in the Java class. Now do you know why the methods in the Java class are written as static? Not why, or willful. Note that this class is abstract, must inherit from it, and has a generic instance that holds a unique instance. Don't take it so much, go on.
Add script UnityPluginTest.cs to the Androidscripts directory with the following code:

     Public classUnityplugintest:androidbehaviour<unityplugintest>    {        protected Override stringJavaclassname {Get{return "Unityplugin. Unityplugintest"; } }         Public Static voidShowtoast (stringMessageBOOLIslong) {instance. Callstatic ("Showtoast", message, Islong); }    }

This is inherited androidbehaviour, and need to implement javaclassname, note that the return value is the package name + class name, what is the package name? Look at the package written at the beginning of the Java code above. Then we write a static method that uses Callstatic to invoke the Showtoast in the Java code. Note the callstatic parameter, the first is the string name of the static method, and the following parameters are consistent with the number and type of the corresponding Java method parameters. The parameter types here only support simple types such as int,float,bool,string.
11. Ok, the plugin is finished. Then write a test code to see.

     Public class Test:monobehaviour    {        void  Update ()        {            if0 && Input.gettouch (0 ). Phase = = Touchphase.began)            {                unityplugintest.showtoast ("Take away your stinking hands!" )   "false);     }}}

12. Create an empty object Androidbridge in the scene and hang up the UnityPluginTest.cs script. Then hang the test script on any object. Add scenes to build settings inside. Complete playersettings various settings, company name, product name, package name.

13. Connect your phone, bold build and run it.

14. After the test pass, you can export the plugin as unitypackage, only need to export the plugins folder, so that in the future can be easily reused.

Integrate various social, billing, push, and other SDKs into Unity plugins

Please make sure that you have fully understood the contents of the first part before continuing.

The space is too long to be sent first. Wait More ...

If you think my article is valuable, I would not mind if I put a "recommendation" or a "concern" ... "White Cat, Blog home: http://www.cnblogs.com/whitecat/"

Using the Android SDK in Unity

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.