Unity3D和iOS的对接及界面跳转


界面1
界面2
界面3
界面4

所需工具:
  1. Unity3d 5.0版本
  2. Xcode 6.2版本 模拟器的操作系统8.2v

步骤1. 创建一个unity项目
  • 创建一个Unity项目,并同时创建一个Cube,一个Text(作为cube的名字)和一个button按钮。如何创建这里就不在叙述,稍后附件中会有源代码。如下图:
创建unity
  • 在Unity的Project栏目的Assests中增加一个.mm文件,文件名自定义,我这里是TNAppController.mm,用xcode编写在拖到这里即可,内容为:
#import <UIKit/UIKit.h>
#import "UnityAppController.h"
#import "UI/UnityView.h"
#import "UI/UnityViewControllerBase.h"
#import "HelloViewController.h"


@interface TNAppController : UnityAppController

@property (nonatomic, strong) UINavigationController *navController;

- (void)willStartWithViewController:(UIViewController*)controller;

@end

@implementation TNAppController

- (void)willStartWithViewController:(UIViewController*)controller
{
    _rootController = [[UIViewController alloc] init];
    _rootView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _rootController.view = _rootView;
    
    HelloViewController *helloVC = [[HelloViewController alloc] initWithNibName:nil bundle:nil];
    self.navController = [[UINavigationController alloc] initWithRootViewController:helloVC];
    [_rootView addSubview:self.navController.view];
}

@end

IMPL_APP_CONTROLLER_SUBCLASS(TNAppController)

说明:
a. 导入的部分都为Untiy生成xcode项目中自带的.h文件,以后再导入也可以,HelloViewController.h文件为我们以后要创建的文件。
b. 这个文件继承UnityAppController.h这个文件,这点很重要,UnityAppController中提供了很多我们可以直接调用的属性,以便我们自己写的iOS文件可以使用window,rootController等属性,这些属性要和Untiy导出的iOS项目使用的是同一个。
c. willStartWithViewController这个方法好像是只有Unity 5左右的版本才用的是这个方法,4.x以前的版本使用的不是这个方法。这个方法是将要打开视图控制器的初始化方法。初始化根视图控制器和根视图。
d. IMPL_APP_CONTROLLER_SUBCLASS 这个很重要,它决定了我们的TNAppController.h 这个文件将被重载。UnityAppController.h 文件中有解释,如下图:

unityAppController.h
  • 在Assets文件夹中,创建一个C# javascript文件,代码如下:
C# javascript脚本文件

说明:
a. [DllImport ("__Internal")] 引入一个dll的内部文件.
b. 声明一个可调用的接口, private static extern int ActivateUI_iOS(int index);该方法可以有任意多个参数,这个参数的使用,到时候我们在iOS模拟器上可以看到,并且可以接收到iOS的返回值。
c. Start方法初始化Button,将button.cs文件与Hierarchy中的创建的Button组件进行关联。

  • 在Assets文件夹中,创建一个test.js文件,代码如下图:
test.js脚本文件

说明:
a. SetText(Input)方法,我们将在ios项目中调用这个方法,动态修改cube的名字。returnVal()方法是没有用的。
b. 我们将test.js文件和Hierarchy中的cube组件关联,在将text组件和cube关联,text组件作为cube组件的名称。

cube组件
  • 我们开始生成IOS项目,unity->file->build & settings,选中iOS,点击player settings,这里就不详细叙述了


步骤2. 配置iOS项目
  • 生成iOS项目目录如下:
生成的iOS目录

我们在untiy中创建的TNAppController.mm文件会出现在Libraries包中,创建的test.js,和button.cs文件会编译成dll.s文件中去
我们在classes文件夹中创建如下文件, MyViewInit.h和MyViewInit.mm文件,mm结尾的,是c++识别的文件,其中有c++代码

  • MyViewInit.h:
//
//  MyViewInit.h
//  Unity-iPhone
//
//  Created by wencun on 4/3/15.
//
//

#import <Foundation/Foundation.h>

@interface MyViewInit : NSObject

+ (void) enabled;
+ (void) disabled;
+ (void) setEnabled:(NSString *)foo;
+ (int) value;
@end

#pragma mark cplusplus code

#ifdef __cplusplus
extern "C" {
#endif
    
    int ActivateUI_iOS(int index);
    
#ifdef __cplusplus
} // extern "C"
#endif
  • MyViewInit.mm:
//
//  MyViewInit.m
//  Unity-iPhone
//
//  Created by wencun on 4/3/15.
//
//

#import "MyViewInit.h"
#import "UnityInterface.h"

@implementation MyViewInit

+ (void) enabled{
    UnitySendMessage("Cube", "Enabled", "");
}

+ (void) disabled{
    UnitySendMessage("Cube", "Disabled", "");
}

+ (void) setEnabled:(NSString *)foo{
    UnitySendMessage("Cube", "SetText", [foo UTF8String]);
}

+ (int) value{
//    return UnitySendMessage("Cube", "returnVal", "");
    return 11;
}

@end

#pragma mark cplusplus code
extern "C"{
    int ActivateUI_iOS(int index){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unity调用了IOS方法" message:[NSString stringWithFormat:@"我是第%i次从Unity过来的!",index] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
//        NSString *s = [NSString stringWithCharacters:index length:99];
//        NSNumber *num = [NSNumber numberWithChar:index];
        return ++index;
    }
}

其中,UnitySendMessage为iOS调用Unity中的方法,第一个参数为组件名称,第二个参数为方法名,第三个参数为方法的参数,该方法的返回值为void,所有不能接受调用Unity方法中的返回值
pragma下方的代码为c++代码,为ActivateUI_iOS的实现,这样,点击Unity中的按钮就可以调用这个方法了,该方法有一个返回值,Unity中可以接收到

  • 创建HelloViewController.h文件,继承UIViewController
//
//  HelloViewController.m
//  Unity-iPhone
//
//  Created by wencun on 4/3/15.
//
//

#import "HelloViewController.h"
#import "CoolUnitySceneviewController.h"

@interface HelloViewController ()

@end

@implementation HelloViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btnNext = [UIButton buttonWithType:UIButtonTypeSystem];
    [btnNext setTitle:@"这是一个IOS界面,点我进入Unity界面。" forState:UIControlStateNormal];
    btnNext.frame = CGRectMake(40, 200, 300, 44);
    btnNext.layer.borderWidth = 1;
//    btnNext.layer.borderColor = [UIColor grayColor];
    btnNext.layer.cornerRadius = 3;
    btnNext.backgroundColor = [UIColor greenColor];
//    btnNext.center = CGPointMake(self.view.bounds.size.height / 2, 200);
    [self.view addSubview:btnNext];
    self.view.backgroundColor = [UIColor grayColor];
    
    [btnNext addTarget:self action:@selector(gotoUnityScene:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Private methods
- (void)gotoUnityScene:(id)sender {
    NSLog(@"[HelloVC] Go to unity scene");
    
    CoolUnitySceneViewController *coolUnityVC = [[CoolUnitySceneViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:coolUnityVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
  • 创建CoolUnitySceneViewController.h文件,继承UIViewController,如下图:
//
//  CoolUnitySceneviewController.m
//  Unity-iPhone
//
//  Created by wencun on 4/3/15.
//
//

#import "CoolUnitySceneViewController.h"
#import "GoodByeViewController.h"
#include "UI/UnityViewControllerBase.h"
#include "UnityAppController+ViewHandling.h"
#import "MyViewInit.h"

@interface CoolUnitySceneViewController ()

@end

@implementation CoolUnitySceneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:GetAppController().unityView];
    
    GetAppController().unityView.frame = self.view.frame;
    
    UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(40, 50, 300, 40)];
    text.text = @"欢迎进入Unity界面!(IOS)";
    text.textAlignment = NSTextAlignmentCenter;
    text.backgroundColor = [UIColor greenColor];
    [self.view addSubview:text];
    
    UITextField *tv = [[UITextField alloc] initWithFrame:CGRectMake(40, 100, 300, 40)];
    tv.textAlignment = NSTextAlignmentCenter;
    tv.layer.borderWidth = 1;
    tv.layer.cornerRadius = 3;
    [tv setPlaceholder:@"请键入文字..."];
    tv.tag = 101;
    [self.view addSubview:tv];
    
    UIButton *btnNext = [UIButton buttonWithType:UIButtonTypeSystem];
    [btnNext setTitle:@"点我可以修改CUBE中的文字(IOS)" forState:UIControlStateNormal];
    btnNext.frame = CGRectMake(40, 150, 300, 44);
    btnNext.backgroundColor = [UIColor whiteColor];
    btnNext.layer.borderWidth = 1;
    btnNext.layer.cornerRadius = 3;
    [self.view addSubview:btnNext];
    
    [btnNext addTarget:self action:@selector(goToLastScene:) forControlEvents:UIControlEventTouchUpInside];

    
    UIButton *recevied = [UIButton buttonWithType:UIButtonTypeSystem];
    [recevied setTitle:@"点我可以进入到另外一个IOS界面哦!(IOS)" forState:UIControlStateNormal];
    recevied.frame = CGRectMake(40, 450, 300, 44);
    recevied.backgroundColor = [UIColor whiteColor];
    recevied.layer.borderWidth = 1;
    recevied.layer.cornerRadius = 3;
    //    btnNext.center = CGPointMake(self.view.bounds.size.height / 2, self.view.bounds.size.width / 2);
    [self.view addSubview:recevied];
    
    [recevied addTarget:self action:@selector(recevied:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Private methods
- (void)goToLastScene:(id)sender {
//    NSLog(@"[CoolUnitySceneVC] Go to the last scene");
    NSString *text = ((UITextField *)[self.view viewWithTag:101]).text;
    if ([text isEqualToString:@""]) {
        text = @"还没有给我一个名字哦!";
    }
    [MyViewInit setEnabled:text];
}

- (void)show:(id)sender{
    [MyViewInit setEnabled:@"show"];
}

- (void)recevied:(id)sender{
        GoodByeViewController *goodByeVC = [[GoodByeViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:goodByeVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

GetAppController().unityView,获取Unity中的视图,把这个视图添加到CoolUnitySceneViewController.h视图上,并设置该视图的框架

  • 创建GoodByeViewController.h文件,代码如下图:
//
//  GoodByeViewController.m
//  Unity-iPhone
//
//  Created by wencun on 4/3/15.
//
//

#import "GoodByeViewController.h"
#import "CoolUnitySceneviewController.h"


@interface GoodByeViewController ()

@end

@implementation GoodByeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayColor];
    
    UILabel *lblTheEnd = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 300, 44)];
    lblTheEnd.text = @"我是第二个IOS界面,欢迎回来!";
    
//    lblTheEnd.center = CGPointMake(self.view.bounds.size.height / 2, self.view.bounds.size.width / 2);
    
    [self.view addSubview:lblTheEnd];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end

做一个UILabel,显示是IOS界面

iOS调用Unity方法的限制:
  1. iOS无法接受到Unity方法中的返回值,因为UnitySendMessage是void的类型
  2. iOS调用Unity方法只能传一个参数,若有多个参数,要拼接成字符串
Unity调用iOS方法:
  1. 调用方法的参数可以有任意个
  2. 可以接受到iOS的返回值
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容