记录UNITY3D与iOS的互相调用,附通用模型

基本交互

标记call函数

1
2
[DllImport ("__Internal")]
private static extern float FooPluginFunction();

使用C来链接被call函数(不使用也可)

1
2
3
extern "C" {
float FooPluginFunction();
}
1
如果不使用可以直接写在.mm文件的 @implemented  @end 之间

在iOS层 使用 UnitySendMessage 函数给Unity场景发送消息

1
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");
  • 必须有同名的GameObject
  • 方法签名必须要对应上
  • UnitySendMessage函数是异步的,会delay一帧,然后被调用。

插件整合方法

  • .m,.mm,.c,.cpp 格式都被支持,需要至于 Plugins/iOS 文件夹下
  • .h 文件不会在Xcode project tree上显示

UnityGameNotification.h - Plugin 通用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
// NSObject+IAPModule.h
// Unity-iPhone
//
// Created by keyle on 11/2/16.
//
//

#import <Foundation/Foundation.h>

@interface IAPModule : NSObject
{
NSString* status;
BOOL searching;
}

- (id)init;
- (int)getCount;
- (NSString *)getStatus;
@end


UnityGameNotification.mm - Plugin 通用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

#import "UnityGameNotification.h"

@implementation NetServiceBrowserDelegate : NSObject
{
NSString* status;
BOOL searching;
}

- (id)init
{
self = [super init];
searching = NO;
status = @"Initializing";
return self;
}

- (void)dealloc
{
// [super dealloc];
}


- (int)getCount
{
return 1024;
}

- (NSString *)getStatus
{
return status;
}

@end

static UnityGameNotification* delegateObject = nil;

// Converts C style string to NSString
NSString* CreateNSString (const char* string)
{
if (string)
return [NSString stringWithUTF8String: string];
else
return [NSString stringWithUTF8String: ""];
}

// Helper method to create C string copy
char* MakeStringCopy (const char* string)
{
if (string == NULL)
return NULL;

char* res = (char*)malloc(strlen(string) + 1);
strcpy(res, string);
return res;
}

// When native code plugin is implemented in .mm / .cpp file, then functions
// should be surrounded with extern "C" block to conform C function naming rules
extern "C" {

void _ExecuteMethodFromiOS (const char* arg1, const char* arg2)
{
//do some initialize work
}

const char* _GetStringFromiOS ()
{
return MakeStringCopy([@"have fun" UTF8String]);
}

int _GetINT ()
{
return 1024;
}

const char* _GetServiceName (int serviceNumber)
{
return MakeStringCopy([@"have fun" UTF8String]);
}
}


参考文档

Building Plugins for iOS