標籤:
Unity調用原生程式方法,定義介面(doTestSelector):
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...
}
}
原生程式實現介面,例如iOS,開啟原生ViewController:
因為需求限制,所以仍然以Objective-C開發
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]);}
Unity調用原生(iOS, Android)方法