IOS原生项目集成Unity3D

一,代码拷贝及项目配置

1,拷贝文件到原生项目
 Libraries 文件夹
 Classes 文件夹
 Data 文件夹
 MapFileParser 文件
2,删除Libraries下的libil2cpp,注意删除选项选择Remove References。
3,添加Unity3D 项目所依赖动态库(参照Unity3D 导出的xCode 工程),并注意Optional 选项
4BD1348B-C4DA-4E39-8E20-554F234709F2.png
4,添加 Other linker Flags 依赖:
            -weak_framework
            CoreMotion
            -weak-lSystem
            -Wl,-undefined,dynamic_lookup

特别注意:如IOS原生项目中配置了-all_load 应删除,否则会与Unity3D 项目中的依赖库冲突

5, "Header Search Paths' 添加Unity3D 文件夹 Classes、Native、include 路径(根据自己项目实际文件路径配置)
            "$(SRCROOT)/FunGaming/3DHuntFish_lib/Classes"
            "$(SRCROOT)/FunGaming/3DHuntFish_lib/Classes/Native"
            "$(SRCROOT)/FunGaming/3DHuntFish_lib/Libraries/libil2cpp/include"
6,添加User-Defined 配置,
4BEADD41-8DC0-40EC-BBA3-05C70870920D.png
 GCC_THUMB_SUPPORT = NO
 GCC_USE_INDIRECT_FUNCTION_CALLS = NO
 UNITY_RUNTIME_VERSION = 2017.3.0f3 // 根据自己Unity 版本实际配置
 UNITY_SCRIPTING_BACKEND = il2cpp
7,添加Build Phases -> Run Script 配置(根据自己项目实际路径配置)
"$PROJECT_DIR/MapFileParser.sh"
rm -rf "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Data"
cp -Rf "$PROJECT_DIR/FunGaming/3DHuntFish_lib/Data" "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Data"

二,代码更改

1,删除Unity3D Class 文件夹下main.mm 文件 并合并到自己原生工程中的main.mm 文件中
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

//int main(int argc, char * argv[]) {
//    @autoreleasepool {
//        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
//    }
//}


#include "RegisterMonoModules.h"
#include "RegisterFeatures.h"
#include <csignal>

// Hack to work around iOS SDK 4.3 linker problem
// we need at least one __TEXT, __const section entry in main application .o files
// to get this section emitted at right time and so avoid LC_ENCRYPTION_INFO size miscalculation
static const int constsection = 0;

void UnityInitTrampoline();

// WARNING: this MUST be c decl (NSString ctor will be called after +load, so we cant really change its value)
const char* AppControllerClassName = "UnityAppController";

int main(int argc, char* argv[])
{
    UnityInitStartupTime();
    @autoreleasepool
    {
        UnityInitTrampoline();
        UnityInitRuntime(argc, argv);
        
        RegisterMonoModules();
        NSLog(@"-> registered mono modules %p\n", &constsection);
        RegisterFeatures();
        
        // iOS terminates open sockets when an application enters background mode.
        // The next write to any of such socket causes SIGPIPE signal being raised,
        // even if the request has been done from scripting side. This disables the
        // signal and allows Mono to throw a proper C# exception.
        std::signal(SIGPIPE, SIG_IGN);
        
        //UIApplicationMain(argc, argv, nil, [NSString stringWithUTF8String: AppControllerClassName]);
        
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
    
    return 0;
}

#if TARGET_IPHONE_SIMULATOR && TARGET_TVOS_SIMULATOR

#include <pthread.h>

extern "C" int pthread_cond_init$UNIX2003(pthread_cond_t *cond, const pthread_condattr_t *attr)
{ return pthread_cond_init(cond, attr); }
extern "C" int pthread_cond_destroy$UNIX2003(pthread_cond_t *cond)
{ return pthread_cond_destroy(cond); }
extern "C" int pthread_cond_wait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex)
{ return pthread_cond_wait(cond, mutex); }
extern "C" int pthread_cond_timedwait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex,
                                               const struct timespec *abstime)
{ return pthread_cond_timedwait(cond, mutex, abstime); }

#endif // TARGET_IPHONE_SIMULATOR && TARGET_TVOS_SIMULATOR
2,UnityAppController.h 中更改
@class AppDelegate;
……
//inline UnityAppController*  GetAppController()
//{
//    return (UnityAppController*)[UIApplication sharedApplication].delegate;
//}

#import "AppDelegate.h"
inline UnityAppController*  GetAppController()
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    return delegate.unityController;
}
3,原生 AppDelegate 中更改

AppDelegate.h:

class UnityAppController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UIWindow *unityWindow;

@property (strong, nonatomic) UnityAppController *unityController;

//- (void)showUnityWindow;
- (void)hideUnityWindow;

/**  通用APP启动接口  */
-(void)commonInitLaunch;

/**  检查APP版本信息  */
-(void)checkAPPVerson;

+(AppDelegate *)sharedDelegate;

-(void)StartMyUnity3DGames; //开启unity

@end

AppDelegate.mm:

#import <UIKit/UIKit.h>
#import "UnityAppController.h"

#import "AppDelegate.h"

-(UIWindow *)unityWindow{
    return  UnityGetMainWindow();
}

-(void)showUnityWindow{
    //进入unity界面
    //[(AppDelegate *)[UIApplication sharedApplication].delegate showUnityWindow];
    
    UnityPause(false);
    
    [self.unityWindow makeKeyAndVisible];
}

-(void)hideUnityWindow{
    
    //推出Unity界面
    //[(AppDelegate *)[UIApplication sharedApplication].delegate hideUnityWindow];
    
    UnityPause(true);
    
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.unityController = [[UnityAppController alloc] init];
    [_unityController application:application didFinishLaunchingWithOptions:launchOptions];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self commonInitLaunch]; // 原生项目启动方法
    
    return YES;
}

+(AppDelegate *)sharedDelegate{
    
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (void)applicationWillResignActive:(UIApplication *)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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
    
    [_unityController applicationWillResignActive:application];
}


- (void)applicationDidEnterBackground:(UIApplication *)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.
    
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
    [_unityController applicationDidEnterBackground:application];
}

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


- (void)applicationDidBecomeActive:(UIApplication *)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.
    
    [[LoginManager instance] startALightWeightHttpServer];
    
    //[_unityController applicationDidBecomeActive:application];
    
}

-(void)StartMyUnity3DGames
{
    [_unityController applicationDidBecomeActive:[UIApplication sharedApplication]];
    
    [self showUnityWindow];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
    [_unityController applicationWillTerminate:application];
}
4 UnityInterface.h 更改
#import <Foundation/Foundation.h> // 引入 objc Foundation 框架

inline char* AllocCString(NSString* value)
{
    if (value == nil)
        return 0;

    const char* str = [value UTF8String];
    return str ? strdup(str) : 0;
}
5,合并 .pch 文件
#include "Preprocessor.h"

#define printf_console printf

#include "UnityTrampolineConfigure.h"
#include "UnityInterface.h"

#if USE_IL2CPP_PCH
#include "il2cpp_precompiled_header.h"
#endif

#ifndef TARGET_IPHONE_SIMULATOR
#define TARGET_IPHONE_SIMULATOR 0
#endif
6, Unity3D 启动及退出

在需要启动Unity3D 项目的地方调用 [[AppDelegate sharedDelegate] StartMyUnity3DGames];
退出Unity3D(其实是暂停) [[AppDelegate sharedDelegate] hideUnityWindow];

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

推荐阅读更多精彩内容