Unity3d tutorial-Passing values between unity script and java using JNI.


       In this article we are going see how to pass the values between unity script and java. Passing values made much easier using JNI. let us discuss various ways to pass values and get values from java class.



   1.Passing values from unity script to java.

 
       Unity Script:
                 //declaring java class
                AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");

                //creating a static object
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
             
                //Calling  non static java method
jo.Call ("trigger", "value to pass");       

 
       Java class:
 
               Declare a non static method in your java class.

             public void trigger(String passedvalue){

                  //Reached to java class

             }

    2.Getting values from java class.


          Let us consider we need to get integer value from the java class.
          we need to declare as follows

     Unity Script:
                 //declaring java class
                AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
                //creating a static object
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
               
                //Calling  non static java method
int Received_integer =jo.Call<int>("trigger");         
   
       Java class:
               Declare a non static method in your java class.
             public void trigger(){
                //Reached to java class
               return 4;
             }


 Note:       Various types of calling method in java class.  

     *Calling a static method without parameters jo.CallStatic ("trigger"); 

     *Calling a static method with parameters jo.CallStatic ("trigger","value to pass");      

     *Calling a non-static method with parameters jo.Call ("trigger","value to pass");  

     *Calling a non-static method without parameters jo.Call ("trigger");


    











Comments