Unity调用原生(iOS, Android)方法

Unity调用原生程序方法,定义接口(doTestSelector),写在Unity的C#代码中,在需要调用iOS或Android中的doTestSelector方法时,触发doTest() : 

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class TestScript : MonoBehaviour {
    // This tells unity to look up the function FooPluginFunction
    // inside the static binary
    [DllImport ("__Internal")]
    private static extern float doTestSelector (string info);

    void doTest () {
#if UNITY_ANDROID
        using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using( AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                jo.Call("doTestSelector", "my info");
            }
        }
#endif
        
#if UNITY_IPHONE
        doTestSelector("my info");
#endif
    }


  public void backToUnity () {
    // Do somthing...
  }

}

 

原生程序对doTestSelector接口的实现,例如iOS,实现写在Unity导出的Xcode项目UnityAppController.mm中:

因为需求限制,所以仍然以Objective-C开发,打开原生ViewController

extern "C" float doTestSelector(const char* info) {
    YourViewController *vc = [[YourViewController alloc] initWithNibName:@"yourViewControllerName" bundle:nil];
    [[UnityGetMainWindow() rootViewController] presentViewController:vc animated:YES completion:nil];
    
    return 0.0f;
}

 

关闭原生程序,回到Unity,同样以iOS为例:

- (IBAction)OnClickBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    UnitySendMessage("TestScriptGameObject", [@"backToUnity" UTF8String], [@"" UTF8String]);
}

 

posted on 2015-09-09 22:11  shawn.zp  阅读(1327)  评论(0编辑  收藏  举报