unity與iOS的交互要比Android之間的簡單,
unity會編譯成xcode的項目以供我們進行二次的開發。
目前我所知道的交互有,unity調用iOS的方法,iOS傳遞字符串給unity兩種
1
隨意創建xcode的項目,
創建一個NSObject類文件,在.h文件
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface AlertView : NSObject
#if defined(__cplusplus)
extern"C"
{
#endif
extern void UnitySendMessage(const char *,const char *, const char *);
#if defined(__cplusplus)
}
#endif
void _showTestView(char *msg);
void _showCompressView (void);
@end
以上的_showTestView(含參數),showCompressView(無參數)是unity調用的方法
在.m文件中,要先實例
static AlertView* alert=nil;
+ (AlertView *) instance{
if (alert==nil)
{
alert=[[AlertView alloc]init];
}
return alert;
}
然後通過alert調用具體的方法
#if defined(__cplusplus)
extern"C"{
#endif
void _showTestView(char *msg){
[AlertView instance];
NSString * stringMsg = [NSString stringWithUTF8String:msg];
[alert showTestView:stringMsg];
}
void _showCompressView (void){
[AlertView instance];
[alert showCompress];
}
#if defined(__cplusplus)
}
#endif
在具體實現_showTestView(含參數),showCompressView(無參數)的方法
- (void)showCompress{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, window.frame.size.width - 150, 50)];
lab.text = @"實現showCompress方法";
lab.textAlignment = 1;
lab.center = CGPointMake(window.frame.size.width / 2 , window.frame.size.height - 40);
[lab setFont:[UIFont systemFontOfSize:20]];
lab.textColor = [UIColor whiteColor];
lab.numberOfLines = 0;
lab.backgroundColor = [UIColor lightGrayColor];
lab.alpha = 0.7;
lab.layer.masksToBounds = YES;
lab.layer.cornerRadius = 10;
[window addSubview:lab];
}
- (void)showTestView:(NSString *)msg{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
[alert show];
//這是將iOS的字符串傳遞到unity中的方法
/*
參數一 unity中的代碼所掛載的物體
參數二 unity中代碼裏面的方法
參數三 所需傳遞的字符串
*/
UnitySendMessage([@"Main Camera" UTF8String],[@"iOS" UTF8String],[@"hello world" UTF8String]);
}
這樣,在iOS中需要做的工作就完成了
將這個類文件複製到unity的文件夾中,一般路徑是Plugins/iOS文件夾中
然後在該文件夾中創建C#代碼,
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public static class IOS
{
[DllImport ("__Internal")]
private static extern void _showTestView(string msg);
[DllImport ("__Internal")]
private static extern void _showCompressView();
public static void showTestView (string msg)
{
_showTestView(msg);
}
public static void showCompressView ()
{
_showCompressView();
}
}
創建一個C#腳本,掛載到物體上,例如Main Camera相機上,
這樣當我們在腳本中調用IOS.showTestView方法,和IOS.showCompressView方法時,就會自動調用到NSObject類中寫好的方法,
同時,在unitySendMessage方法會返回一個“hello world”字符串到Main Camera物體上的iOS方法,所以我們要在腳本中創建一個方法
void iOS (string msg){
Debug.Log (msg);
}
然後打包成xcode項目,就可以看到能夠正常運行了,具體代碼不寫了,這個不難理解。