Unity: Call android function from Unity

后端 未结 3 562
梦如初夏
梦如初夏 2020-12-13 11:22
AndroidJavaClass unityPlayer = new AndroidJavaClass(\"com.unity3d.player.UnityPlayer\");

AndroidJavaObject activity = unityPlayer.GetStatic(\"currentActivity\");

a         


        
相关标签:
3条回答
  • 2020-12-13 12:04

    While you might have fixed the issue, I believe the real issue lies elsewhere. I've helped create quite a few plugins for Unity, so I'm just going to put in my thoughts here for you to read and for anyone else who might face the same or similar issues.

    Firstly, you've used a UIThread to call your non-static, public method. This is perfectly fine, but only if some UI operation is performed in the native code, such as showing a toast. Otherwise, the issue lies elsewhere.

    Usually, if you create a method, it's going to be in a separate class that extends the UnityPlayerActivity. So for an example, let's say you've called it "MyClass.java"

    This is probably how your Java Native class looks like

    Native Android Code

    package com.companyName.productName;
    
    import com.unity3d.player.UnityPlayerActivity;
    import com.unity3d.player.UnityPlayer;
    
    public class MyClass extends UnityPlayerActivity {    
    
        public void testMethod(String data) { 
            Log.i("TAG", "The data was "+data);
        }
    }
    


    Now on the Unity side, your C# script should look like this

    Unity C# code

    AndroidJavaClass myClass = new AndroidJavaClass("com.companyName.productName.MyClass");
    
    myClass.Call("testMethod", new object[] { "testString" } );
    


    Note how I've used the actual Java Class rather than the UnityPlayerActivity (i.e. "com.companyName.productName.MyClass" rather than "com.unity3d.player.UnityPlayer")


    Try the code above, it should print "The data was testString" to the logcat.

    In your C# code, you've used the currentActivity field to call your method.

    Rather, what you want to do is to create an AndroidJavaObject or AndroidJavaClass of your class that extends UnityPlayerActivity ("MyClass.java" in the above example) and call your methods.

    0 讨论(0)
  • 2020-12-13 12:13

    Declare testMethod(public) you in .jar file?

    If you don't declare method, you try make .jar file.

    0 讨论(0)
  • 2020-12-13 12:22

    It should work. Actually I'm using non-static method calling like yours.

    Did you update your jar file under Assets/Plugins/Android?

    0 讨论(0)
提交回复
热议问题