Unity3d Research Institute and Android Mutual messaging

Source: Internet
Author: User

Original address: http://www.xuanyusong.com/archives/676

in the previous article, we learned that unity sends messages to Android, and if Android can give unity back messages, then it's a beautiful game. Just as Unity for Andoid and iOS are all capable of sending and receiving messages to unity with each other, this article Momo a good chat about how Android sends messages to unity. Before reading the blog post, I suggest that you read my previous article Unity3d Research Institute of Open activity and call Java Code Pass parameters (18), about the data packaging aspects in the previous article has been said very clearly, here will not repeat.

We create two activities in the project one is the main activity one is the newly opened activity and content aspect similar to the previous article.

Unitytestactivity.java main activity, provides an interface method StartActivity (), which is called by unity

 PackageCom.xys;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.os.Bundle;Importcom.unity3d.player.UnityPlayerActivity; Public classUnitytestactivityextendsunityplayeractivity {/**Called when the activity is first created.*/Context Mcontext=NULL; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Mcontext= This; }      Public voidStartActivity0 (String name) {Intent Intent=NewIntent (mcontext,testactivity0.class); Intent.putextra ("Name", name);  This. StartActivity (Intent); } }

Then Testactivity.java opens the interface, where the program will send a message to unity.

 PackageCom.xys;ImportCom.unity3d.player.UnityPlayer;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classTestActivity0extendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);         Setcontentview (R.layout.main); TextView text= (TextView) This. Findviewbyid (R.id.textview1); Text.settext ( This. Getintent (). Getstringextra ("name")); FinalEditText edit = (EditText) This. Findviewbyid (R.id.edit); Button Close= (Button) This. Findviewbyid (R.id.button0); Close.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//Note 1Unityplayer.unitysendmessage ("Main Camera", "Messgae", Edit.gettext (). toString ()); TestActivity0. This. Finish ();    }        }); } }

Need to introduce package import Com.unity3d.player.UnityPlayer in the program header; Because the static method of sending messages to unity is written here.

Note 1: This means that the program sends a message to unity after clicking the Send button. The Unityplayer.unitysendmessage () parameter 1 represents the name of the sending game object, and Parameter 2 represents the method by which the object-bound script receives the message, and Parameter 3 represents the string information sent by this message, much like the way iOS sends a message.

Then we opened the Unity project to pack the Android plugin for replication in the Unity project, and in the detailed packaging process, see a chapter that binds the script Test.cs to the main camera object, at this point because The Unityplayer.unitysendmessage () method sends a message to the Maincamera object, so it needs to receive the message in the script bound to the main camera object, that is, to receive it in the Test.cs script.

(Larger picture, click to view the larger image)

Now let's look at the Test.cs script

usingUnityengine;usingSystem.Collections; Public classtest:monobehaviour{//Please enter a string    Private stringStringtoedit ="Please enter a string"; voidUpdate () {//Click the Phone Back button to close the app        if(Input.getkeydown (keycode.escape) ¦¦input.getkeydown (keycode.home)) {application.quit (); }    }     voidOngui () {//Draw an input box to receive user inputStringtoedit = Guilayout.textfield (Stringtoedit, Guilayout.width ( -), Guilayout.height ( -)); //a Submit button        if(Guilayout.button ("Commit", Guilayout.height ( -)))        {            //Note 1              using(Androidjavaclass JC =NewAndroidjavaclass ("Com.unity3d.player.UnityPlayer"))            {                 using(Androidjavaobject Jo = JC.) getstatic< Androidjavaobject> ("currentactivity"))                {                    //call the StartActivity0 method in Unitytestactivity in the Android plug-in, Stringtoedit represents its argumentsJo. Call ("StartActivity0", Stringtoedit); }             }         }     }    //NOTE 2    voidMessgae (stringstr) {Stringtoedit=str; } }

Note 1: Putting the code in the using is to tell the garbage collector to recycle the garbage in a timely manner, so it is recommended to write the code. Androidjavaclass represents a Java class, Androidjavaobject represents a Java object, which is clearly stated in the previous chapter. In addition, there are other methods, such as calling static methods, are written in the API is very clear, you can read the study.

Note 2: The method just called Unityplayer.unitysendmessage () Parameter 2 is "message", so the program calls the message method of the Test.cs script of the Main camera object, and the parameters are passed over to Android. Finally, this modifies the Stringtoedit variable to refresh the UI of the screen.

After opening the program will launch Unity screen, as here we wrote the input box to receive the user's keyboard input, the last user click on the Commit button program will open Android activity, and will be the string "Please enter a string" Passed as a parameter to the new activity.

As shown in the newly opened activity, you have already seen the Please enter a string string already displayed in the interface, in the layout file also wrote the Android Advanced control input box and button, enter the string "Xuanyusong" in the input box (any input) , clicking the Save button will pass the string "Xuanyusong" just entered to unity.

As shown, the string "Xuanyusong" in Unity is now displayed in the input box, so this is perfect for sending and receiving messages. I hope you will continue to support the MOMO Program Research Institute.

Source:Http://vdisk.weibo.com/s/abEoV

    • This article fixed link: http://www.xuanyusong.com/archives/676

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.