和上一篇类似,我们同样希望Unity能够直接调用IOS底层的代码,那么我们就需要研究怎么去实现它。下面让我来带大家看一个简单的例子
1.创建.h和.m文件如下
.h
// // myTest.m // Unity-iPhone // // Created by Mount on 16/2/18. // // #import <Foundation/Foundation.h> @interface MyTest : NSObject @end
.m
// MyTest.m #import "MyTest.h" #if defined(__cplusplus) extern "C"{ #endif extern void UnitySendMessage(const char *, const char *, const char *); extern NSString* _CreateNSString (const char* string); #if defined(__cplusplus) } #endif //***************************************************************************** @implementation MyTest // 初始化SDK -(void)SDKInit { // 弹出框测试 UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"Title" message:@"123" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alter show]; } @end //***************************************************************************** #if defined(__cplusplus) extern "C"{ #endif // 字符串转化的工具函数 NSString* _CreateNSString (const char* string) { if (string) return [NSString stringWithUTF8String: string]; else return [NSString stringWithUTF8String: ""]; } char* _MakeStringCopy( const char* string) { if (NULL == string) { return NULL; } char* res = (char*)malloc(strlen(string)+1); strcpy(res, string); return res; } static MyTest *mytest; // 供u3d调用的c函数 const char* _PlatformInit() { if(mytest==NULL) { mytest = [[MyTest alloc]init]; } [mytest SDKInit]; return _MakeStringCopy("3334434534543543"); } #if defined(__cplusplus) } #endif
2.将.h和.m拷贝到Assets下你的ios目录下面
3.编写C#脚本调用代码
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class animationplay : MonoBehaviour { // 导入定义到.m文件中的C函数 [DllImport("__Internal")] private static extern string _PlatformInit(); // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI(){ // create button to play animate if (GUI.Button (new Rect (Screen.width / 2 + 230, Screen.height / 2 + 50, 100, 40), "clickanimate")) { Animator ani = this.gameObject.GetComponent<Animator>(); ani.Play("animation", -1, 0f); ani.Update(0f); } // create button to call ios SDK if (GUI.Button (new Rect (Screen.width / 2 + 230, Screen.height / 2, 100, 40), "callSDK")) { string returnstring = _PlatformInit(); } } }
4.把这个脚本绑定到物体上,然后导出xcode项目,用xcode连接真机就可以看到结果。如下