Android& Unity3D - 函数调用转到错误的线程

时间:2014-05-20 00:45:44

标签: c# android multithreading unity3d

所以我创建了一个在Unity游戏中显示广告的插件。在Unity中,我想调用扩展UnityPlayerActivity的类中的方法。以下是我com/mycompany/mygame/MainActivity.java的一些代码:

public class MainActivity extends UnityPlayerActivity {

    private static AdView adView;

    // Code the initializes the ad view goes here
    ...

    public static void hideAd() {
        adView.setVisibility(View.INVISIBLE);
    }

    public static void showAd() {
        adView.setVisibility(View.VISIBLE);
    }
}

hideAd()showAd()是我希望能够从Unity调用的方法。在Unity中,这里有一些示例代码,我必须测试我的插件:

AndroidJavaClass ajc;
bool ohBool = true;

void Update () {
    foreach (Touch touch in Input.touches) {
        if (touch.phase == TouchPhase.Began) {
            // Call my function
            float touchLoc = Camera.main.ScreenToWorldPoint(touch.position).y;
            if (touchLoc > 0.0f) {
                if (showAd) {
                    ajc.CallStatic("hideAd");
                    showAd = false;
                }
                else {
                    ajc.CallStatic("showAd");
                    showAd = true;
                }
            }
        }
    }
}

然而,只要发生这些函数调用,LogCat就会向我吐出:

AndroidJavaException: android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.

我该怎么办?

编辑:以下是我要求的初始化代码:

void Start() {
    AndroidJNI.AttachCurrentThread();
    ajc = new AndroidJavaClass("com.mycompany.mygame.MainActivity");
}

1 个答案:

答案 0 :(得分:2)

首先尝试附加当前线程。

void Start() {
    AndroidJNI.AttachCurrentThread();
    AndroidJavaClass ajc = new AndroidJavaClass("com.mycompany.mygame.MainActivity"); //This is your java class hierarchy
    ajc.CallStatic("showAd");
}