Swift4整合Unity

前面的部分和其他版本大同小异
可以参考Swift3整合Unity5.6

这篇文章再介绍基本的集成内容中,还会补充一些上述文章中没有提到的内容,填了不少的坑

开始吧~~~~~

1. 添加Unity.xcconfig文件到项目

//
//  Unity.xcconfig
UNITY_RUNTIME_VERSION = 5.6.1;//U3D版本
UNITY_SCRIPTING_BACKEND = il2cpp;
GCC_THUMB_SUPPORT = NO;
GCC_USE_INDIRECT_FUNCTION_CALLS = NO
UNITY_IOS_EXPORT_PATH = $(PROJECT_DIR)/unity_ios;//U3D存放目录
GCC_PREFIX_HEADER = $(UNITY_IOS_EXPORT_PATH)/Classes/Prefix.pch;

OTHER_LDFLAGS = -weak-lSystem -weak_framework CoreMotion -weak_framework GameKit -weak_framework iAd -framework CoreGraphics -framework AVFoundation -framework CoreVideo -framework CoreMedia -framework SystemConfiguration -framework CoreLocation -framework MediaPlayer -framework CFNetwork -framework AudioToolbox -framework OpenAL -framework QuartzCore -framework OpenGLES -framework UIKit -framework Foundation -liconv.2 -liPhone-lib;//添加的动态库

HEADER_SEARCH_PATHS = $(inherited) $(UNITY_IOS_EXPORT_PATH) $(UNITY_IOS_EXPORT_PATH)/Classes $(UNITY_IOS_EXPORT_PATH)/Classes/Native $(UNITY_IOS_EXPORT_PATH)/Classes/UI $(UNITY_IOS_EXPORT_PATH)/Libraries $(UNITY_IOS_EXPORT_PATH)/Libraries/libil2cpp/include $(UNITY_IOS_EXPORT_PATH)/Libraries/bdwgc/include;
LIBRARY_SEARCH_PATHS = $(inherited) $(UNITY_IOS_EXPORT_PATH) $(UNITY_IOS_EXPORT_PATH)/Libraries $(UNITY_IOS_EXPORT_PATH)/Libraries/libil2cpp/include;

ENABLE_BITCODE = NO;

//请根据自己的项目修改
SWIFT_OBJC_BRIDGING_HEADER = $(PROJECT_DIR)/$(PRODUCT_NAME)/UnityBridge.h;

OTHER_CFLAGS = -DINIT_SCRIPTING_BACKEND=1;
CLANG_CXX_LANGUAGE_STANDARD = compiler-default;
CLANG_CXX_LIBRARY = libc++;
CLANG_WARN_BOOL_CONVERSION = NO;
CLANG_WARN_CONSTANT_CONVERSION = NO;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES;
CLANG_WARN_EMPTY_BODY = NO;
CLANG_WARN_ENUM_CONVERSION = NO;
CLANG_WARN_INT_CONVERSION = NO;
CLANG_WARN_OBJC_ROOT_CLASS = YES;
CLANG_WARN_UNREACHABLE_CODE = NO;
CLANG_WARN__DUPLICATE_METHOD_MATCH = NO;
GCC_C_LANGUAGE_STANDARD = c99;
GCC_ENABLE_OBJC_EXCEPTIONS = NO;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_THUMB_SUPPORT = NO;
GCC_USE_INDIRECT_FUNCTION_CALLS = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION[arch=*64] = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = NO;
GCC_WARN_UNINITIALIZED_AUTOS = NO;
GCC_WARN_UNUSED_FUNCTION = NO;
GCC_NO_COMMON_BLOCKS = NO;
CLANG_ENABLE_MODULES = NO;

CLANG_WARN_DOCUMENTATION_COMMENTS = NO;

CLANG_WARN_EMPTY_BODY = NO;
CLANG_WARN_INFINITE_RECURSION = NO;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = NO;
CLANG_WARN_UNREACHABLE_CODE = NO;

GCC_WARN_UNUSED_FUNCTION = NO;

CLANG_WARN__DUPLICATE_METHOD_MATCH = NO;

添加Unity.xcconfig后如下图做相应配置

如果没有集成cocoapods的情况下

Snip20180208_50.png

如果集成cocoapods的情况下

Snip20180208_51.png

2. 添加UnityBridge.h UnityUtils.h UnityUtils.mm 到项目

Snip20180208_52.png
//
//  UnityBridge.h
//
//  Created by Adam Venturella on 10/28/15.
//

#ifndef UnityBridge_h
#define UnityBridge_h

#import "UnityUtils.h"
#import "UnityAppController.h"
#import "Unity/UnityInterface.h"
#endif /* UnityBridge_h */



/**
 * Replacement Function for UnityAppController.h
 *
 */
/*
 NS_INLINE UnityAppController* GetAppController(){
 NSObject<UIApplicationDelegate>* delegate = [UIApplication sharedApplication].delegate;
 UnityAppController* currentUnityController = (UnityAppController *)[delegate valueForKey:@"currentUnityController"];
 return currentUnityController;
 }
 */

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//
//  UnityUtils.h
//
//  Created by Adam Venturella on 10/28/15.
//

#ifndef UnityUtils_h
#define UnityUtils_h


void custom_unity_init(int argc, char* argv[]);

#endif /* UnityUtils_h */

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//
//  UnityUtils.m
//
//  Created by Adam Venturella on 10/28/15.
//
// this is taken directly from the unity generated main.mm file.
// if they change that initialization, this will need to be updated
// as well.


#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();


extern "C" void custom_unity_init(int argc, char* argv[])
{
    @autoreleasepool
    {
        UnityInitTrampoline();
//        UnityParseCommandLine(argc, argv); //Unity 5.3+
        UnityInitRuntime(argc, argv); //Unity 5.6+,5.4和5.5用哪个我没试过,可以根据报错情况选择。
        
        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);
    }
}

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

3. 将Unity导出的文件导入到xcode工程中

Snip20180208_53.png

4.设置配置

image.png

注意注意!!!这个很重要 debug和release都要加上-DRUNTIME_IL2CPP=1否则打包的版本就会有问题
Snip20180208_56.png

注意注意!!!一般我们只需要加-DRUNTIME_IL2CPP=1,如果出现
was compiled with optimization - stepping may behave oddly; variables may not be available.
加要加上

I had the same issue and I solve it adding to Apple LLVM - Custom Compiler FLags:

Other C Flags: -DRUNTIME_IL2CPP=1

5.变更Unity里的方法

找到main.mm

//int main(int argc, char* argv[])
//{
//    signed long long startTime = mach_absolute_time();
//    @autoreleasepool
//    {
//        UnitySetStartupTime(startTime);
//        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 0;
//}
//替换为
int main_unity_default(int argc, char* argv[])
{
    @autoreleasepool
    {
        UnityInitTrampoline();
//        UnityParseCommandLine(argc, argv); //Unity 5.3+
        UnityInitRuntime(argc, argv); //Unity 5.6+,5.4和5.5用哪个我没试过,可以根据报错情况选择。
        
        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]);
        //        UIApplicationMain(argc, argv, nil, NSStringFromClass([UnitySubAppDelegate class]));
        UIApplicationMain(argc, argv, nil, [NSString stringWithUTF8String:AppControllerClassName]);
    }
    
    return 0;
}

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

找到UnityAppController.h

#import <UIKit/UIKit.h>
//注释该方法
//inline UnityAppController*  GetAppController()
//{
//    return (UnityAppController*)[UIApplication sharedApplication].delegate;
//}
//替换为此方法
NS_INLINE UnityAppController* GetAppController()
{
    NSObject<UIApplicationDelegate>* delegate = [UIApplication sharedApplication].delegate;
    UnityAppController* currentUnityController = (UnityAppController *)[delegate valueForKey:@"currentUnityController"];
    return currentUnityController;
}

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

找到SplashScreen类 修改这个方法,之前忘记加上

void ShowSplashScreen(UIWindow* window)
{
    _controller = [[SplashScreenController alloc] init];
    [_controller create: window];
}

添加一个新的main.swift文件到项目

//
//  main.swift
//  SwiftCombineUnityProject
//
//  Created by Stefans on 2017/6/15.
//  Copyright © 2017年 Stefans. All rights reserved.
//

import Foundation
import UIKit

custom_unity_init(CommandLine.argc, CommandLine.unsafeArgv)

UIApplicationMain(
    CommandLine.argc,
    UnsafeMutableRawPointer(CommandLine.unsafeArgv)
        .bindMemory(
            to: UnsafeMutablePointer<Int8>.self,
            capacity: Int(CommandLine.argc)),
    nil,
    NSStringFromClass(AppDelegate.self)
)

作者:Stefans23
链接:https://www.jianshu.com/p/a3df2922d98d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

找到AppDelegate.swift并作如下修改

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        window?.backgroundColor = UIColor.white;
        window?.rootViewController = ViewController();
        
        currentUnityController = UnityAppController()
        currentUnityController.application(application, didFinishLaunchingWithOptions: launchOptions)

        window!.makeKeyAndVisible()
        return true
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        currentUnityController.applicationWillResignActive(application)
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        currentUnityController.applicationDidEnterBackground(application)
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        currentUnityController.applicationWillEnterForeground(application)
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        currentUnityController.applicationDidBecomeActive(application)
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        currentUnityController.applicationWillTerminate(application)
    }

OK~~~一切都搞定了
显示U3D view

        let unityview = UnityGetGLView()
        unityview?.frame = CGRect(x:0,y:0,width:self.view.frame.width,height:self.view.frame.size.height/2);
        unityview?.center = self.view.center
        self.view.addSubview(unityview!)
        self.view.bringSubview(toFront: unityview!)

如果出现AVFoundationMediaLoader之类的错误
添加mediatool

总结一下~

接进去就是一个大坑,不是领导要求我才不接.....

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

推荐阅读更多精彩内容