首页 > 代码库 > unity3d与Object-C交互

unity3d与Object-C交互

(1)unity3d 中如何调用IOS的Api

1、在C# 脚本中使用

 (1) 需要导入文件 using System.Runtime.InteropServices; 

 (2) [System.Runtime.InteropServices.DllImport("__Internal")]

      extern static public int AwesomeFunction(int awesomeParameter);

2、在unity导出的xcode工程中的C/C++/objective-C 文件中的任意位置, 新建一个类 unityplugin.h, unityplugin.mm

头文件中:

extern "C" void AwesomeFunction();

 类体中:

int AwesomeFunction(int awesomeParameter)

{

     return somethingAwesome;

}

 

具体的:

 

Unity C# 代码

using UnityEngine;using System.Collections;using System.Runtime.InteropServices;public class testFeil : MonoBehaviour {        [DllImport("__Internal")]    private static extern void c_ctest();        void Start () {    }    void Update () {    }        void OnGUI()      {          //开始按钮  创建了一个按钮。          if(GUI.Button(new Rect(20,100,200,50),"qingyun "))          {               c_ctest();          }          } 
// 这个是C#里的一个回调。OC处理完成后 调用Unity方法
void testFaildResult (string msg) { Debug.Log("testResult:" +msg); } //这个是C#里的一个回调。这里的作用就是OC里的回调函数。 void testSuccessResult (string msg) { Debug.Log ("btnPressSuccess:"+msg); }}

Object-C  .mm 文件里的OC  与 C 接口

 

MeiyuPushSdk.h

#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>@protocol  MeiyuPushSdkDelegate;
@interface MeiyuPushSdk : NSObject@property (nonatomic, assign)id<MeiyuPushSdkDelegate> delegate;//初始化+(MeiyuPushSdk*)my_initPush;+ (void)my_setupWithOption:(NSDictionary *)launchingOption registerForRemoteNotificationTypes:(int)types ; // 注册APNS类型+ (void)my_registerDeviceToken:(NSData *)deviceToken; // 向服务器上传Device Token+ (void)my_receiveRemoteNotification:(NSDictionary *)remoteInfo; // 处理收到的APNS消息,向服务器上传收到APNS消息-(void)cTest;@end@protocol MeiyuPushSdkDelegate <NSObject>@optional-(void)cTestResult;@end

 

MeiyuPushSdkC.h

#import <Foundation/Foundation.h>#ifdef __cplusplusextern "C"{#endif    void c_ctest();  #ifdef __cplusplus}#endif

MeiyuPushSdkC.mm

#import "MeiyuPushSdkC.h"#import "MeiyuPushSdk.h"@interface MeiyuPushSdkC : NSObject<MeiyuPushSdkDelegate>@end@implementation MeiyuPushSdkC- (id)init{    id object = [super init];    [[MeiyuPushSdk my_initPush]setDelegate:self];    NSLog(@"initMeiyuPushSdkC");    return object;}-(void)cTestResult{    UnitySendMessage("Main Camera", "testSuceessResult", "成功");}@endMeiyuPushSdkC *m_pushSdk = NULL;#if defined (__cplusplus)extern "C"{#endif    void c_ctest()    {        if(m_pushSdk == NULL)        {            m_pushSdk = [[MeiyuPushSdkC alloc]init];        }        MeiyuPushSdk *m = [MeiyuPushSdk my_initPush];        [m cTest];
UnitySendMessage("Main Camera", "testFaildResult", "接口调用失败"); } #if defined (__cplusplus)}#endif

这样就把Unity3d 与OC 连到了一起。