Rifat
Rifat

Reputation: 1888

Access method from android plugin in unity

This is pretty basic, but I'm not getting success on implementing it from the official Unity docs and YouTube video tutorials, so I asked.

I want to access methods from already made aar plug-in. Its checked as android plug-in by default. The plug-in has following code:

package alarm.company.com.unity;

public class myPlugin {

    public String myTest(int i){
        return "Hello your string number is: "+i;
    }

}

the compiled aar plug-in is copied into the Unity folder. Here's the c# code to access that method:

const string PluginName = "alarm.company.com.unity.myPlugin";
static AndroidJavaClass _pluginClass;
static AndroidJavaClass _pluginInstance;

public Text text;

// Start is called before the first frame update
void Start()
{

    AndroidJavaClass plugin = new AndroidJavaClass(PluginName);
    string s = plugin.CallStatic<string>("myTest", 9);
    print(s);
    text.text = s;

}

text is assigned and this script is put on the main camera. But I'm not getting any text back or the text object is not changed, while running in emulator. How can this be solved?

Upvotes: 1

Views: 2532

Answers (2)

Nikolay Gonza
Nikolay Gonza

Reputation: 613

Some advises when you work with plugins for unity:

  1. Use gradle build system. It generates mainTemplate file in Plugins/Android. You can edit this file and set source java code to your java classes so you don't need to generate aar every time you want to build:

    sourceSets 
    {
        main
        {
            java
            {
                srcDirs = ['src']
                srcDirs += ['E:/AndroidStudioProjects/PathToJavaClasses']
            }
        }
    }
    
  2. If you want to send something from java code to unity you should extend your activity from unity and call method UnitySendMessage

    public class MyUnityPlayerActivity extends UnityPlayerActivity{
        public void SendUnityMessage()
        {
             UnityPlayer.UnitySendMessage(UnityGameObjectName, UNITY_FUNCTION_NAME, 
             params);
        }
    }
    

Upvotes: 0

ChillBroDev
ChillBroDev

Reputation: 312

Unity Plugin development is a bit tricky to get setup at first but once you are able to it is pretty powerful.

Couple things.

1) You are using an AndroidJavaClass and trying to call a non static method in java. Your method in your plugin should be static if you are wanting to use that class.

2) Otherwise you will need to use an AndroidJavaObject to construct your class and then you should be able to call your function.

Hope this helps!

Example Using non Static Code:

Unity Code

   using (AndroidJavaObject leetPlugin = new AndroidJavaObject("alarm.company.com.unity.myPlugin")){
        string s = leetPlugin.Call("myTest", 9);
        print(s);
        text.text = s;
    } 

Android Code

public void myTest(int value) {
   return "Your value is " + value;
}

Upvotes: 2

Related Questions