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的情况下

Swift4整合Unity_第1张图片
Snip20180208_50.png

如果集成cocoapods的情况下

Swift4整合Unity_第2张图片
Snip20180208_51.png

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

Swift4整合Unity_第3张图片
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* 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 


// 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工程中

Swift4整合Unity_第4张图片
Snip20180208_53.png

4.设置配置

Swift4整合Unity_第5张图片
image.png

注意注意!!!这个很重要 debug和release都要加上 -DRUNTIME_IL2CPP=1否则打包的版本就会有问题
Swift4整合Unity_第6张图片
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 
//注释该方法
//inline UnityAppController*  GetAppController()
//{
//    return (UnityAppController*)[UIApplication sharedApplication].delegate;
//}
//替换为此方法
NS_INLINE UnityAppController* GetAppController()
{
    NSObject* 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.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

总结一下~

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

你可能感兴趣的:(Swift4整合Unity)