简体   繁体   English

从统一C#调用Java方法

[英]calling java method from unity c#

Hello everyone, Can anyone tell me how to call java methods from unity c#. 大家好,谁能告诉我如何从统一c#调用Java方法。 I tried the following but its not working for me. 我尝试了以下方法,但对我不起作用。

In Unity : 在Unity中:

void OnGUI () {
    string somestring;
    AndroidJavaClass jc= new    AndroidJavaClass("com.example.pluginsample.MainActivity");
    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("instance");
    somestring = jo.Call<string>("Foo");
    GUI.Label (new Rect (20, 20, 100, 20), somestring);
}

In Java Class: 在Java类中:

public String Foo()
{
    return "Hello";        
}

Please help.I am stuck.Thanks in advance. 请帮助。我被困住了。谢谢。

Exactly what "isn't working"? 究竟是什么“不起作用”? Is there an exception? 有例外吗?

Check your java class has an instance() method that returns the java object: 检查您的Java类是否具有返回Java对象的instance()方法:

public String Foo()
{
    return "Hello";        
}

public static MainActivity instance() {
    return new MainActivity();
}

There are several things to be checked: 有几件事要检查:

  1. Have you declared your plugin activity to AndroidManifest.xml? 您是否已将插件活动声明为AndroidManifest.xml?
  2. Is there any instance class property (static variable) in you plugin activity? 插件活动中是否有任何instance类属性(静态变量)?
  3. If two points above doesnt help, can you make the Foo method to be static? 如果以上两点无济于事,您可以使Foo方法为静态方法吗?

Let me know if this solution still does not work. 让我知道此解决方案是否仍然无效。

The similar question I saw on unity forum. 我在统一论坛上看到过类似的问题。 Do have a look at the question and solution for that. 请查看有关此问题和解决方案 Its working. 它的工作。

Make the function “Foo” public static as below 使函数“ Foo”成为公共静态,如下所示

public static String Foo()
{
    return "Hello";        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM