UnitySendMessage这个方法相信很少朋友注意到它的使用,因为根本就无法在unity编辑时使用,但是它有一个神奇的地方就是可以完成dllimport的方法回调时使用,这样说好像有些抽象,我可以举一个例子。
很多朋友开发ios客户端游戏,难免有人会用到付费啊,排行榜之类的功能,我这里先不讲使用什么第三方插件什么的,我这里就说明下是通过在xcode下编辑相关的调用代码,最后通过dllimport方法让unity调用实现两边通信。
相信上面说的dllimport方法也有人了解过,这时候重点来了,如果用户付费,肯定会有一个结果,比如付费成功,付费失败这样,xcode底下是挂一个notification就是有点类似于监听器的东西,当有一个结果返回时就调用,这时候怎么办?xcode下的回调方法我在unity下怎么知道它什么时候回调过来?于是UnitySendMessage这个方法就诞生了,在回调方法被触发时,我们通过UnitySendMessage方法把结果发给unity,让unity这边处理。
UnitySendMessage(“string”,“string”, ***),这是方法,我们至少需要传入两个参数,第一个参数为unity中的一个gameobject名称,第二个参数为这个gameobject身上捆绑的脚本中的一个方法,而第三参数事实上是这个对应方法上的参数,有没有参数就看你了。
|
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
|
@implementation UnityNdComPlatformDelegate+
(void)addNdComPlatformObservers{ [[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(loginFinished:)
name:kNdCPLoginNotification object:nil]; [[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(buyFinished:)
name:kNdCPBuyResultNotification object:nil]; [[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(leavePlatform:)
name:kNdCPLeavePlatformNotification object:nil]; [[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(sessionInvalid:)
name:kNdCPSessionInvalidNotification object:nil];} +
(void)sendU3dMessage:(NSString *)messageName
param:(NSDictionary *)dict{ NSString *param
= @""; for (NSString *key
in dict) { if ([param
length] == 0) { param
= [param stringByAppendingFormat:@"%@=%@",
key, [dict valueForKey:key]]; } else { param
= [param stringByAppendingFormat:@"&%@=%@",
key, [dict valueForKey:key]]; } } UnitySendMessage("MyMsgObj",
[messageName UTF8String], [param UTF8String]);} +
(void)loginFinished:(NSNotification *)aNotify{/**
登录接口通知 **/ NSDictionary *dict
= [aNotify userInfo]; [self sendU3dMessage:@"kNdCPLoginNotification" param: [NSDictionary dictionaryWithObjectsAndKeys:[dict
objectForKey:@"result"],
@"result",
[dict objectForKey:@"error"],
@"error", nil]];} |
这里我贴一个91平台的调用理念,一开始我们通过addNdComPlatformObservers方法增加监听,当登陆回调方法loginFinished被触发时,我们通过sendU3dMessage方法调用UnitySendMessage把具体的登陆结果传回到unity。

UnitySendMessage方法常被忽视,但它在DLLImport回调中发挥重要作用,例如在iOS游戏开发中处理付费和排行榜功能。通过Xcode编辑调用代码,结合dllimport,当Xcode端收到如付费成功/失败的结果时,可以利用UnitySendMessage将结果通知给Unity进行处理。UnitySendMessage需要指定GameObject的名称、其上的脚本方法名,以及可选的参数,实现跨平台通信。
4万+

被折叠的 条评论
为什么被折叠?



