iOS和unity的交互问题

之前完全没接触过unity,因为现在公司需要在unity的代码上做二次开发,所以我要能够随意调用unity的方法,在网上搜了很多种方法都没什么用,全是几年前的版本,我只是在别人原来的方法上更新下,写一个最新版本的交互例子。   我用的是unity5.3和Xcode7.3

 创建一个按钮直接跳转到unity项目的方法网上可以搜到,我就不做描述了

这里只说怎样随意调用unity里单个的方法

创建unity场景这个可以通过

雨松momo大神的方法来弄 http://www.xuanyusong.com/archives/517

 

 

 

 

我的方法就是在他的基础上更新了一下,主要是他那个版本是很老的,不适用现在的版本

 

导出成iOS后我创建了一个类叫MyView  

 

 MyView.h文件

#import <UIKit/UIKit.h>

@interface MyView : NSObject
+(void)CreateButton:title rect:(CGRect)rect action:(SEL)action controller:(UIViewController *)controller;
+(void)CreateTitle:(UIViewController *)controller;
+(void)LeftButtonPressed;
+(void)RightButtonPressed;
+(void)UpButtonPressed;
+(void)DownButtonPressed;
+(void)Init:(UIViewController *)controller;
@end

MyView.mm文件

#import "MyView.h"

@interface MyView ()

@end

@implementation MyView


//创建按钮
+(void)CreateButton:title rect:(CGRect)rect action:(SEL)action controller:(UIViewController *)controller
{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    //设置按钮范围
    btn.frame = rect;
    
    //设置按钮显示内容
    [btn setTitle:title forState:UIControlStateNormal];
    
    //设置按钮改变后绑定的响应方法
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    
    //加入View中
    [controller.view addSubview:btn];
}


//创建标签
+(void)CreateTitle:(UIViewController *)controller
{
    //创建label视图
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    //设置显示内容
    label.text = @"旋转控制";
    //设置背景颜色
    label.backgroundColor = [UIColor blueColor];
    //设置文字颜色
    label.textColor = [UIColor whiteColor];
    //设置显示位置居中
    label.textAlignment = NSTextAlignmentCenter;
    //设置字体大小
    label.font = [UIFont fontWithName:[[UIFont familyNames] objectAtIndex:10] size:20];
    
    [controller.view addSubview:label];
}


//向左按钮
+(void)LeftButtonPressed
{
    UnitySendMessage("Cube", "MoveLeft","");
}

//向右按钮
+(void)RightButtonPressed
{
    UnitySendMessage("Cube", "MoveRight","");
}
//向上按钮
+(void)UpButtonPressed
{
    UnitySendMessage("Cube", "MoveUp","");
}

//向下按钮
+(void)DownButtonPressed
{
    UnitySendMessage("Cube", "MoveDown","");
}


+(void)Init:(UIViewController *)controller
{
    [self CreateTitle:controller];
    
    [self CreateButton:@"左旋转" rect:CGRectMake(0,  50, 100, 40) action:@selector(LeftButtonPressed) controller:controller];
    [self CreateButton:@"右旋转" rect:CGRectMake(0, 100, 100, 40) action:@selector(RightButtonPressed) controller:controller];
    [self CreateButton:@"上旋转" rect:CGRectMake(0, 150, 100, 40) action:@selector(UpButtonPressed) controller:controller];
    [self CreateButton:@"下旋转" rect:CGRectMake(0, 200, 100, 40) action:@selector(DownButtonPressed) controller:controller];
}



@end

 

然后进入UnityAppController.mm里

 

在UnityAppController.mm里面导入头文件

 

 

找到这一行

 

 

在这个方法里的return YES 之前加上这段代码

 

 

然后运行就出现了这个界面

 

 

 

点击按钮后这个模型会旋转

 

好了,就是这些

posted @ 2016-07-04 19:01  大王叫我来巡山诶  阅读(314)  评论(0编辑  收藏  举报