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

一、合并iOS工程和u3d工程

将成型的iOS工程嵌入到u3d工程中_第1张图片
待合并的两个工程

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 

#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 
@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脚本中的方法为静态方法时,这个方法无效,所以只能调用非静态的方法

(四)、合并后的截图

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

将成型的iOS工程嵌入到u3d工程中_第2张图片
合并后的工程

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

你可能感兴趣的