将成型的iOS工程嵌入到u3d工程中

一、合并iOS工程和u3d工程

待合并的两个工程

1、一个U3d导出的Xcode工程Unity-iPhone,单独编译运行OK
2、一个iOS工程ARHere,单独编译运行OK
3、打开终端cd 到Unity-iPhone文件夹,vim Podfile,把ARHere的内容复制粘贴,pod install --verbose --no-repo-update
4、打开Unity-iPhone文件夹中的Unity-iPhone.xcworkspace,不要急着做其他事情,先配置好
5、在build pathless 中的 link binary with libraries 中增加原iOS工程ARHere的库文件(Unity-iPhone工程已经有了的就不用加了,第三方.a的待会文件复制会自动带过来)

 ->(Accelerate.framework ,AssetsLibrary.framework  这两个是因为报了的Undefined symbols for architecture arm64 xxx错误才加,不一定非要)

6、在build setting 修改如下参数

Build Options —————> Enable BItcode  ————> NO
Linking ——>  Other Linker Flags———>$(inherited)
Search Paths ————> User Header Search Paths ——————> ${SRCROOT}  , 改成递归模型(recursive)

如果出现这样的错误的话试试这样
d: warning: directory not found for option '-L"/Users/mlmk/Desktop/最新合并AR工程/10.31/Libraries"'
ld: library not found for -liPhone-lib

在Search Paths ——> Library searcher path 中将“$(SRCROOT)/Libraries”  把这个双引号去除掉


像这样的Undefined symbols for architecture arm64 xxx
Undefined symbols for architecture armv7:
就是缺少.framework库文件支持啦,自己搞一搞

7、最后加入ARHere工程的文件,
(1)、对pct文件合并,之后保留一个,要U3d工程的就不需要修改pch引用路径。
(2)、对info.plist文件合并,比如你用了微信第三方登录等,就会有URL和像https访问限制等其他配置,要保留进去
(3)、项目的启动图LaunchScreen、运用图标AppIcon在U3d导出的Xcode工程中的某个文件夹就有了,前提是你要在打包U3d Xcode工程中Player setting中设置了。
(4)、main.m可以删除了,如果是storyboard启动的,最好改成代码启动
(5)、对app delegate文件做继承操作

#import <UIKit/UIKit.h>

#import "UnityAppController.h"

@interface UnitySubAppDelegate : UnityAppController

@end

#import "UnitySubAppDelegate.h"
#import "HomePageController.h"

IMPL_APP_CONTROLLER_SUBCLASS(UnitySubAppDelegate)// 指定启动文件类

/**
 *  如果你的U3d工程集成了EasyAR的SDK,在Libraries/Plugins/IOS/下会有这么个文件
*    EasyARAppController.mm,它也是集成了UnityAppController的,所以你要把它内容复制粘贴到你自己的app delegate文件中,然后干掉他
 */
extern "C" void ezarUnitySetGraphicsDevice(void* device, int deviceType, int eventType);
extern "C" void ezarUnityRenderEvent(int marker);
@interface UnitySubAppDelegate () {
    HomePageController *_homeVC;
}
- (void)shouldAttachRenderDelegate;
@end

@implementation UnitySubAppDelegate

- (void)shouldAttachRenderDelegate;
{
    UnityRegisterRenderingPlugin(&ezarUnitySetGraphicsDevice, &ezarUnityRenderEvent);
}
- (void)startUnity:(UIApplication *)application {
   [super startUnity:application]; //先启动unity
// 再启动我们自己的界面,如何如何这都得看你自己的需求
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    HomePageController *homeVC = [storyboard instantiateViewControllerWithIdentifier:@"homeVC"];
    UIView *homeView = homeVC.view;
    homeView.backgroundColor = [UIColor clearColor];
    _homeVC = homeVC;
    [UnityGetGLView()  addSubview: homeView];
}


- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [super application:application didFinishLaunchingWithOptions:launchOptions];
    

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [super applicationWillResignActive:application];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [super applicationDidEnterBackground:application];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [super applicationWillEnterForeground:application];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [super applicationDidBecomeActive:application];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [super applicationWillTerminate:application];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

二、后期U3d修改操作

因为平台的原因每次U3d修改之后,又得重新打一个xcode工程包,这样调试效率着实很慢,我没有找到实时联调的办法,有的话就请留言告诉我一声。但替换还是很快很简单的不需要像上面那么多步骤。

1、因为合并的环境已经OK了,再次合并只需要把最新的U3d工程的class、data、Library替换掉就好了(当然如果你在UnityAppController.mm做了修改,那就先替换这个文件啦)
2、如果合并不成功,各种系统报错,搞了一会没搞定,那就建议你重新合并一遍吧,不用太纠结啦,划不来多少时间的。
3、如果你换U3d版本或者xcode版本了,替换又是各种系统问题,那还是建议你重新合并一遍吧,不用太纠结啦,划不来多少时间的。

三、iOS和U3d的交互

(1)、合并之后会有很多交互的地方,我的办法是:凡是U3d调用iOS的方法全部放在一个类里面管理


#import <Foundation/Foundation.h>
@interface u3dRequest : NSObject
@end

#if defined(__cplusplus)
extern "C"{
#endif
    extern void loadHomePage(); //无参无返回
    
    extern void u3dRequestDataFromIos(const char *paraJson); // 有参无返回
    
    extern const char* u3dGetAlbumPathFromios();// 有返回无参数
    
#if defined(__cplusplus)
}
#endif
#import "u3dRequest.h"
@implementation u3dRequest
@end

#ifdef __cplusplus
extern "C"{
#endif
    void loadHomePage(){
        UnitySubAppDelegate *appDelegate = (UnitySubAppDelegate *)[UIApplication sharedApplication].delegate;
        UIView *homeView= [appDelegate.homeVC getHomeView];
        [UnityGetGLView() addSubview:homeView ];
        
    }
    
    void u3dRequestDataFromIos(const char *paraJson) {
//        把格式化的JSON格式的字符串转换成字典
        NSString *jsonStr = [NSString stringWithUTF8String:paraJson];
         NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
         NSError *err;
         NSMutableDictionary *u3dParaDic = [NSJSONSerialization JSONObjectWithData:jsonData
         options:NSJSONReadingMutableContainers
         error:&err];
         if(err) {
             NSLog(@"json解析失败:%@",err);
             return ;
         }
        NSString *typeFunction = u3dParaDic[@"mCmd"];

        [u3dParaDic removeObjectForKey:@"mCmd"];

        NSDictionary *params =  [[SingleRequestParam sharedSingleton]requestWithDic:u3dParaDic];
        NSString *url = [NSString stringWithFormat:@"%@%@",BaseURL,u3dParaDic[@"url"]];
     
        [HYBNetworking postWithUrl:url refreshCache:YES params:params success:^(id response) {
            
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
            [resultDic setObject:typeFunction forKey:@"mCmd"];
            [resultDic addEntriesFromDictionary:response];
            NSError *parseError = nil;
            
            NSData *resultJsonData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:&parseError];
            
           NSString    *resultJsonString  = [[NSString alloc] initWithData:resultJsonData encoding:NSUTF8StringEncoding];
            DBLog(@"u3dRequestDataFromIos resultJsonString = %@",resultJsonString);
            char * resultJson_char = (char *)malloc(strlen([resultJsonString UTF8String]) + 1);
            strcpy(resultJson_char, [resultJsonString UTF8String]);
            UnitySendMessage("PlatformSys", "ReceiveGameJson", resultJson_char);
           
        } fail:^(NSError *error) {
            
            NSMutableDictionary *errorDic = [NSMutableDictionary dictionary];
            [errorDic setObject:typeFunction forKey:@"mCmd"];
            [errorDic setObject:@"网络连接错误!" forKey:@"errmsg"];
            NSError *parseError = nil;
            NSData *resultJsonData = [NSJSONSerialization dataWithJSONObject:errorDic options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString   *errorJsonString  = [[NSString alloc] initWithData:resultJsonData encoding:NSUTF8StringEncoding];
            char * errorJson_char = (char *)malloc(strlen([errorJsonString UTF8String]) + 1);
            strcpy(errorJson_char, [errorJsonString UTF8String]);
            UnitySendMessage("PlatformSys", "ReceiveGameJson", errorJson_char);
             NSLog(@"网络连接错误!");
        }];
    }
    
   
    const char* u3dGetAlbumPathFromios(){
        //获取沙盒路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
         NSString *imagePath=[NSString stringWithFormat:@"%@/MyAlbum",path];
        // 判断文件夹是否存在,如果不存在,则创建
        if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
        } else {
            NSLog(@"imagePath is exists.");
        }
       char * imagePath_char = (char *)malloc(strlen([imagePath UTF8String]) + 1);
       strcpy(imagePath_char, [imagePath UTF8String]);
       return imagePath_char;
    }

    
#ifdef __cplusplus
}
#endif

(2)、iOS 调用U3d就超级简单了,一句代码,放在你需要调用的任何地方

UnityPlayer.UnitySendMessage("Main Camera", "AgentPurchaseCancelled",msg);

参数一为unity脚本挂载的gameobject
参数二为unity脚本中要调用的方法名
参数三为传递的参数
这个方法是没有返回值的
当unity脚本中的方法为静态方法时,这个方法无效,所以只能调用非静态的方法

(四)、合并后的截图

最后的结果就是这样子的啦

合并后的工程

(1)、你的iOS工程最好搞成是真实文件夹对应的,这样一拉过来就行
(2)、main.mm 用U3d工程的
(3)、Assets.xcassets 是原来iOS工程切图,U3d工程的Images.xcassets主要是启动图和app图标(如果启动made with unity 图,那是U3d自带的,可以在player settings 勾选掉 貌似要破解版的或者付费版的)

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

推荐阅读更多精彩内容