最近公司要開發一款用於3d展示的應用,通過在網上拜讀各大神的帖子,終於完美解決此類問題。(unity3d版本2017.3,xcode9.2)
前邊unity3d打包iOS工程的方法在此就不做贅述,其他帖子基本可以解決,本帖直接上乾貨。
1、在打包好的iOS工程中,找到UnityAppController.m文件(在classes文件夾下),因爲我們需要3d物體和控件同屏,所以要首先改造- (void)applicationDidBecomeActive:(UIApplication*)application;這個方法。具體代碼如下:
- (void)applicationDidBecomeActive:(UIApplication*)application
{
::printf("-> applicationDidBecomeActive()\n");
if(_unityAppReady)
{
if(UnityIsPaused())
{
UnityPause(0);
UnityWillResume();
}
UnitySetPlayerFocus(1);
}
else if(!_startUnityScheduled)
{
_startUnityScheduled = true;
[self performSelector:@selector(startUnity:) withObject:application afterDelay:0];
}
_didResignActive = false;
static dispatch_once_t disOnce;
dispatch_once(&disOnce, ^ {
[self performSelector:@selector(startViewC:) withObject:application afterDelay:0];
});
NSLog(@"_window22222222%@",_window.rootViewController);
}
-(void)startViewC:(UIApplication *)application{
//自己的需要進入的視圖
MyViewController *root = [[MyViewController alloc] init];
_window.rootViewController = root;
GetAppController().unityView.frame = CGRectMake(0, 0, 512, 768);//我這裏只對ipad進行了適配
root.controller = GetAppController();//controller是一個UnityAppController類型
}
2、在我們自己的controller中進行iOS代碼處理,MyViewcontroller.h
#import <UIKit/UIKit.h>
#import "UnityAppController.h"
@interface MyViewController : UIViewController
@property(nonatomic, strong) UIView *vw;
@property(nonatomic)UnityAppController *controller;
@end
MyViewcontroller.m
#import "MyViewController.h"
@interface MyViewController ()
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIView *uview = [[UIView alloc] initWithFrame:CGRectMake(512, 0, 512, 768)];
[self.view addSubview:uview];
[uview addSubview:self.controller.unityView];
//除了uview之外的區域,iOS的控件就可以按自己的項目需求處理了。
}
@end
通過上邊的操作基本上已經解決了iOS和unity同窗的問題,如還有疑問或者覺得寫的有錯誤的地方可以留言。