当前位置:   article > 正文

Unity与iOS交互(2)——接入SDK_unity 与ios交互

unity 与ios交互

【前言】

接入Android和iOS SDK有很多相同的地方,建议先看下Android SDK如何接入

 【UnityAppController详解】

 整个程序的入口在MainApp文件下的main.mm文件中,先加载了unityframework,然后调用runUIApplicationMain。源码如下:(这些源码在Xcode工程里都有)

  1. #include <UnityFramework/UnityFramework.h>
  2. UnityFramework* UnityFrameworkLoad()
  3. {
  4. NSString* bundlePath = nil;
  5. bundlePath = [[NSBundle mainBundle] bundlePath];
  6. bundlePath = [bundlePath stringByAppendingString: @"/Frameworks/UnityFramework.framework"];//获取完整的UnityFramework的路径
  7. NSBundle* bundle = [NSBundle bundleWithPath: bundlePath];
  8. if ([bundle isLoaded] == false) [bundle load];//调用bunlde加载接口加载,bundle表示一个包含代码、资源和其他文件的目录或者是一个.framework文件
  9. //UnityFramework类的头文件是UnityFramework.h,实现文件在Classes文件夹中的main.mm
  10. UnityFramework* ufw = [bundle.principalClass getInstance];//获取bundle主类示例,主类是一个UnityFramework,bundle 只有一个主类,该类通常是应用程序的控制器类
  11. if (![ufw appController]) //调用appController方法获取,第一次获取的为空
  12. {
  13. // unity is not initialized
  14. [ufw setExecuteHeader: &_mh_execute_header];//设置头信息,初始化unity引擎
  15. }
  16. return ufw;
  17. }
  18. int main(int argc, char* argv[])//main是整个应用程序的入口,和什么语言没关系,一般都是这样
  19. {
  20. @autoreleasepool //创建一个自动释放池
  21. {
  22. id ufw = UnityFrameworkLoad();//先加载了UnityFramework
  23. [ufw runUIApplicationMainWithArgc: argc argv: argv];//runUIApplicationMainWithArgc,这个方式是UnityFramework.h中的方法
  24. return 0;
  25. }
  26. }

可以看看UnityFramework.h文件中定义的函数

  1. #import <UIKit/UIKit.h>
  2. #import <Foundation/Foundation.h>
  3. #import "UnityAppController.h"
  4. #include "UndefinePlatforms.h"
  5. #include <mach-o/ldsyms.h>
  6. typedef struct
  7. #ifdef __LP64__
  8. mach_header_64
  9. #else
  10. mach_header
  11. #endif
  12. MachHeader;
  13. #include "RedefinePlatforms.h"
  14. //! Project version number for UnityFramework.
  15. FOUNDATION_EXPORT double UnityFrameworkVersionNumber;
  16. //! Project version string for UnityFramework.
  17. FOUNDATION_EXPORT const unsigned char UnityFrameworkVersionString[];
  18. // In this header, you should import all the public headers of your framework using statements like #import <UnityFramework/PublicHeader.h>
  19. #pragma once
  20. // important app life-cycle events
  21. __attribute__ ((visibility("default")))
  22. @protocol UnityFrameworkListener<NSObject>
  23. @optional
  24. - (void)unityDidUnload:(NSNotification*)notification;
  25. - (void)unityDidQuit:(NSNotification*)notification;
  26. @end
  27. __attribute__ ((visibility("default")))
  28. @interface UnityFramework : NSObject
  29. {
  30. }
  31. - (UnityAppController*)appController;
  32. + (UnityFramework*)getInstance;
  33. - (void)setDataBundleId:(const char*)bundleId;
  34. - (void)runUIApplicationMainWithArgc:(int)argc argv:(char*[])argv;
  35. - (void)runEmbeddedWithArgc:(int)argc argv:(char*[])argv appLaunchOpts:(NSDictionary*)appLaunchOpts;
  36. - (void)unloadApplication;
  37. - (void)quitApplication:(int)exitCode;
  38. - (void)registerFrameworkListener:(id<UnityFrameworkListener>)obj;
  39. - (void)unregisterFrameworkListener:(id<UnityFrameworkListener>)obj;
  40. - (void)showUnityWindow;
  41. - (void)pause:(bool)pause;
  42. - (void)setExecuteHeader:(const MachHeader*)header;
  43. - (void)sendMessageToGOWithName:(const char*)goName functionName:(const char*)name message:(const char*)msg;
  44. @end

函数实现在Classes文件夹下的main.mm文件中

  1. #include "RegisterFeatures.h"
  2. #include <csignal>
  3. #include "UnityInterface.h"
  4. #include "../UnityFramework/UnityFramework.h"
  5. void UnityInitTrampoline();
  6. // WARNING: this MUST be c decl (NSString ctor will be called after +load, so we cant really change its value)
  7. const char* AppControllerClassName = "UnityAppController";
  8. #if UNITY_USES_DYNAMIC_PLAYER_LIB
  9. extern "C" void SetAllUnityFunctionsForDynamicPlayerLib();
  10. #endif
  11. extern "C" void UnitySetExecuteMachHeader(const MachHeader* header);
  12. extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidUnload;
  13. extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidQuit;
  14. @implementation UnityFramework
  15. {
  16. int runCount;
  17. }
  18. UnityFramework* _gUnityFramework = nil;
  19. + (UnityFramework*)getInstance
  20. {
  21. if (_gUnityFramework == nil)
  22. {
  23. _gUnityFramework = [[UnityFramework alloc] init];//获取单例时先调用alloc分配内存,再调用init初始化
  24. }
  25. return _gUnityFramework;
  26. }
  27. - (UnityAppController*)appController
  28. {
  29. return GetAppController(); //调用UnityAppController.mm中的方法
  30. }
  31. - (void)setExecuteHeader:(const MachHeader*)header
  32. {
  33. UnitySetExecuteMachHeader(header);//一个 Unity 引擎的函数,用于设置当前可执行文件的 Mach-O 头信息,header是一个指向可执行文件 Mach-O 头信息的指针
  34. }//在 macOS 或 iOS 上,可执行文件的 Mach-O 头信息包含有关可执行文件的元数据,例如文件类型、CPU 架构、入口点和段信息。Unity 引擎使用该函数来设置当前可执行文件的 Mach-O 头信息,以确保 Unity 引擎可以正确加载并执行游戏逻辑。
  35. - (void)sendMessageToGOWithName:(const char*)goName functionName:(const char*)name message:(const char*)msg
  36. {
  37. UnitySendMessage(goName, name, msg);
  38. }
  39. - (void)registerFrameworkListener:(id<UnityFrameworkListener>)obj
  40. {
  41. #define REGISTER_SELECTOR(sel, notif_name) \
  42. if([obj respondsToSelector:sel]) \
  43. [[NSNotificationCenter defaultCenter] addObserver:obj selector:sel name:notif_name object:nil];
  44. REGISTER_SELECTOR(@selector(unityDidUnload:), kUnityDidUnload);
  45. REGISTER_SELECTOR(@selector(unityDidQuit:), kUnityDidQuit);
  46. #undef REGISTER_SELECTOR
  47. }
  48. - (void)unregisterFrameworkListener:(id<UnityFrameworkListener>)obj
  49. {
  50. [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidUnload object: nil];
  51. [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidQuit object: nil];
  52. }
  53. - (void)frameworkWarmup:(int)argc argv:(char*[])argv
  54. {
  55. #if UNITY_USES_DYNAMIC_PLAYER_LIB
  56. SetAllUnityFunctionsForDynamicPlayerLib();
  57. #endif
  58. UnityInitTrampoline();
  59. UnityInitRuntime(argc, argv);
  60. RegisterFeatures();
  61. // iOS terminates open sockets when an application enters background mode.
  62. // The next write to any of such socket causes SIGPIPE signal being raised,
  63. // even if the request has been done from scripting side. This disables the
  64. // signal and allows Mono to throw a proper C# exception.
  65. std::signal(SIGPIPE, SIG_IGN);
  66. }
  67. - (void)setDataBundleId:(const char*)bundleId
  68. {
  69. UnitySetDataBundleDirWithBundleId(bundleId);
  70. }
  71. - (void)runUIApplicationMainWithArgc:(int)argc argv:(char*[])argv
  72. {
  73. self->runCount += 1;
  74. [self frameworkWarmup: argc argv: argv];
  75. UIApplicationMain(argc, argv, nil, [NSString stringWithUTF8String: AppControllerClassName]);
  76. //UIApplicationMain是iOS应用程序的入口点,一般在入口main函数中调用,unity在frameworkWarmup后调用,其用于启动应用程序并设置应用程序的主运行循环(main run loop)
  77. //该方法有4个参数,第三个参数是NSString类型的principalClassName,其是应用程序对象所属的类,该类必须继承自UIApplication类,如果所属类字符串的值为nil, UIKit就缺省使用UIApplication类
  78. //第四个参数是NSString类型的delegateClassName,其是应用程序类的代理类,该函数跟据delegateClassName创建一个delegate对象,并将UIApplication对象中的delegate属性设置为delegate对象,这里创建了UnityAppController,看其头文件是继承了UIApplicationDelegate
  79. //该函数创建UIApplication对象和AppDelegate对象,然后将控制权交给主运行循环,等待事件的发生。UIApplicationMain还会创建应用程序的主窗口,并将其显示在屏幕上,从而启动应用程序的UI界面。
  80. }
  81. - (void)runEmbeddedWithArgc:(int)argc argv:(char*[])argv appLaunchOpts:(NSDictionary*)appLaunchOpts
  82. {
  83. if (self->runCount)
  84. {
  85. // initialize from partial unload ( sceneLessMode & onPause )
  86. UnityLoadApplicationFromSceneLessState();
  87. UnitySuppressPauseMessage();
  88. [self pause: false];
  89. [self showUnityWindow];
  90. // Send Unity start event
  91. UnitySendEmbeddedLaunchEvent(0);
  92. }
  93. else
  94. {
  95. // full initialization from ground up
  96. [self frameworkWarmup: argc argv: argv];
  97. id app = [UIApplication sharedApplication];
  98. id appCtrl = [[NSClassFromString([NSString stringWithUTF8String: AppControllerClassName]) alloc] init];
  99. [appCtrl application: app didFinishLaunchingWithOptions: appLaunchOpts];
  100. [appCtrl applicationWillEnterForeground: app];
  101. [appCtrl applicationDidBecomeActive: app];
  102. // Send Unity start (first time) event
  103. UnitySendEmbeddedLaunchEvent(1);
  104. }
  105. self->runCount += 1;
  106. }
  107. - (void)unloadApplication
  108. {
  109. UnityUnloadApplication();
  110. }
  111. - (void)quitApplication:(int)exitCode
  112. {
  113. UnityQuitApplication(exitCode);
  114. }
  115. - (void)showUnityWindow
  116. {
  117. [[[self appController] window] makeKeyAndVisible];
  118. }
  119. - (void)pause:(bool)pause
  120. {
  121. UnityPause(pause);
  122. }
  123. @end
  124. #if TARGET_IPHONE_SIMULATOR && TARGET_TVOS_SIMULATOR
  125. #include <pthread.h>
  126. extern "C" int pthread_cond_init$UNIX2003(pthread_cond_t *cond, const pthread_condattr_t *attr)
  127. { return pthread_cond_init(cond, attr); }
  128. extern "C" int pthread_cond_destroy$UNIX2003(pthread_cond_t *cond)
  129. { return pthread_cond_destroy(cond); }
  130. extern "C" int pthread_cond_wait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex)
  131. { return pthread_cond_wait(cond, mutex); }
  132. extern "C" int pthread_cond_timedwait$UNIX2003(pthread_cond_t *cond, pthread_mutex_t *mutex,
  133. const struct timespec *abstime)
  134. { return pthread_cond_timedwait(cond, mutex, abstime); }
  135. #endif // TARGET_IPHONE_SIMULATOR && TARGET_TVOS_SIMULATOR

调用UIApplicationMain创建了UnityAppController之后,接收iOS系统事件通知即可,接收通知的处理在 UnityAppController.mm文件中。下面是与生命周期相关的事件

先是willFinishLaunchingWithOptions,只发了个通知

  1. - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  2. {
  3. AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
  4. return YES;
  5. }
  6. void AppController_SendNotificationWithArg(NSString* name, id arg) //Unity引擎用于在iOS平台上发送消息通知的方法
  7. {
  8. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
  9. }

随后是didFinishLaunchingWithOptions

  1. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  2. {
  3. ::printf("-> applicationDidFinishLaunching()\n");
  4. // send notfications
  5. #if !PLATFORM_TVOS
  6. #pragma clang diagnostic push
  7. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  8. if (UILocalNotification* notification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey])
  9. UnitySendLocalNotification(notification);
  10. if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
  11. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  12. #pragma clang diagnostic pop
  13. #endif
  14. //UnityDataBundleDir()是一个用于获取Unity数据包目录的方法,它返回一个NSString对象,表示Unity数据包的路径
  15. //随后初始化Unity应用程序,但不会创建图形界面
  16. UnityInitApplicationNoGraphics(UnityDataBundleDir());
  17. [self selectRenderingAPI];//在iOS平台上,Unity引擎通常支持OpenGL ES和Metal两种渲染API,该方法会根据具体的设备和系统版本等因素来动态地选择使用哪种渲染API
  18. [UnityRenderingView InitializeForAPI: self.renderingAPI];//UnityRenderingView是用于呈现Unity引擎场景的iOS视图,InitializeForAPI是UnityRenderingView的初始化方法,self.renderingAPI表示Unity引擎所选的渲染API
  19. #if (PLATFORM_IOS && defined(__IPHONE_13_0)) || (PLATFORM_TVOS && defined(__TVOS_13_0))
  20. if (@available(iOS 13, tvOS 13, *))
  21. _window = [[UIWindow alloc] initWithWindowScene: [self pickStartupWindowScene: application.connectedScenes]];
  22. else
  23. #endif
  24. //UIWindow是iOS中的一个视图对象,用于展示应用程序的用户界面.它是一个特殊的视图,通常作为应用程序中所有视图的容器。在iOS中,每个应用程序都有一个主窗口,即UIWindow对象,它是整个应用程序界面的根视图。所有其他的视图都是添加到UIWindow对象中的。
  25. //UIWindow对象还可以响应用户的触摸事件和手势,同Android一样,Untiy会自己渲染视图,但需要使用操作系统提供的触摸事件
  26. _window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
  27. //创建UnityRenderingView对象,而不是使用iOS系统的视图对象,如UIView或UIWindow,这个视图对象会放入UIWindow中
  28. _unityView = [self createUnityView];
  29. [DisplayManager Initialize];//unity的显示器管理类初始化,unity使用DisplayManager来管理显示器并在多个显示器上呈现Unity场景
  30. _mainDisplay = [DisplayManager Instance].mainDisplay;//设置主显示器
  31. [_mainDisplay createWithWindow: _window andView: _unityView];//将iOS的窗口UIWindow和Unity的RenderingView同主显示器关联起来
  32. [self createUI];//用于创建iOS应用程序界面中的常规视图对象,例如按钮、标签、文本框等
  33. [self preStartUnity];//预启动,在unity启动前可以注册插件
  34. // if you wont use keyboard you may comment it out at save some memory
  35. [KeyboardDelegate Initialize];
  36. return YES;
  37. }

之后是applicationDidBecomeActive

  1. - (void)applicationDidBecomeActive:(UIApplication*)application
  2. {
  3. ::printf("-> applicationDidBecomeActive()\n");
  4. [self removeSnapshotViewController];//删除iOS应用程序窗口中的快照视图控制器
  5. //在iOS应用程序中,当应用程序进入后台时,系统会自动截取当前应用程序的截图,以便在应用程序再次进入前台时快速还原应用程序的状态。\
  6. //这个截图被称为快照(Snapshot),而用于管理快照的视图控制器被称为快照视图控制器(Snapshot View Controller)
  7. //unity自己渲染画面,不需要
  8. if (_unityAppReady)//从后台切换到前台时
  9. {
  10. if (UnityIsPaused() && _wasPausedExternal == false)
  11. {
  12. UnityWillResume();//会调用OnApplicaionFous
  13. UnityPause(0);
  14. }
  15. if (_wasPausedExternal)
  16. {
  17. if (UnityIsFullScreenPlaying())
  18. TryResumeFullScreenVideo();
  19. }
  20. // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
  21. [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
  22. UnitySetPlayerFocus(1);
  23. }
  24. else if (!_startUnityScheduled)//刚打开游戏app走这里,调用startUnity
  25. {
  26. _startUnityScheduled = true;
  27. [self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
  28. }
  29. _didResignActive = false;
  30. }
  31. - (void)startUnity:(UIApplication*)application
  32. {
  33. NSAssert(_unityAppReady == NO, @"[UnityAppController startUnity:] called after Unity has been initialized");
  34. UnityInitApplicationGraphics();//初始化Unity引擎的图形渲染
  35. // we make sure that first level gets correct display list and orientation
  36. [[DisplayManager Instance] updateDisplayListCacheInUnity];
  37. UnityLoadApplication();
  38. Profiler_InitProfiler();//初始化Profiler
  39. [self showGameUI];
  40. [self createDisplayLink];
  41. UnitySetPlayerFocus(1);
  42. AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  43. [audioSession setCategory: AVAudioSessionCategoryAmbient error: nil];
  44. if (UnityIsAudioManagerAvailableAndEnabled())
  45. {
  46. if (UnityShouldPrepareForIOSRecording())
  47. {
  48. [audioSession setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
  49. }
  50. else if (UnityShouldMuteOtherAudioSources())
  51. {
  52. [audioSession setCategory: AVAudioSessionCategorySoloAmbient error: nil];
  53. }
  54. }
  55. [audioSession setActive: YES error: nil];
  56. [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
  57. UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
  58. #if UNITY_REPLAY_KIT_AVAILABLE
  59. void InitUnityReplayKit(); // Classes/Unity/UnityReplayKit.mm
  60. InitUnityReplayKit();
  61. #endif
  62. }

再后是进入后台进入前台

  1. - (void)applicationDidEnterBackground:(UIApplication*)application
  2. {
  3. ::printf("-> applicationDidEnterBackground()\n");
  4. }
  5. - (void)applicationWillEnterForeground:(UIApplication*)application
  6. {
  7. ::printf("-> applicationWillEnterForeground()\n");
  8. // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
  9. if (_unityAppReady)
  10. {
  11. // if we were showing video before going to background - the view size may be changed while we are in background
  12. [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
  13. }
  14. }

最后是applicationWillResignActive

  1. - (void)applicationWillResignActive:(UIApplication*)application
  2. {
  3. ::printf("-> applicationWillResignActive()\n");
  4. if (_unityAppReady)
  5. {
  6. UnitySetPlayerFocus(0);
  7. // signal unity that the frame rendering have ended
  8. // as we will not get the callback from the display link current frame
  9. UnityDisplayLinkCallback(0);
  10. _wasPausedExternal = UnityIsPaused();
  11. if (_wasPausedExternal == false)
  12. {
  13. // Pause Unity only if we don't need special background processing
  14. // otherwise batched player loop can be called to run user scripts.
  15. if (!UnityGetUseCustomAppBackgroundBehavior())
  16. {
  17. #if UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE
  18. // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
  19. // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
  20. // NB: We will actually pause after the loop (when calling UnityPause).
  21. UnityWillPause();
  22. [self repaint];
  23. UnityWaitForFrame();
  24. [self addSnapshotViewController];
  25. #endif
  26. UnityPause(1);
  27. }
  28. }
  29. }
  30. _didResignActive = true;
  31. }

【接入SDK】

总体上和Android没什么区别,相比Andorid好点是不用做Jar,因为本质上是C#调用C,C调用OC,一些需要的编译在出包的时候都会编译好。

同样的看是否需要生命周期,不需要生命周期的自己写调用即可。如果需要生命周期,同样是需要继承的,在Android中继承的是Activiry,在iOS就是要继承UnityAppController。

在Plugins/iOS路径下创建CustomAppController.mm​文件。(文件名必须是 ___AppController,前缀可自选,但不能省略;否则在 Build 项目的时候,会被移动到错误的目录中去。)文件主要代码如下:

  1. @interface CustomAppController : UnityAppController
  2. @end
  3. IMPL_APP_CONTROLLER_SUBCLASS (CustomAppController)
  4. @implementation CustomAppController
  5. //重写生命周期函数
  6. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  7. {
  8. [super application:application didFinishLaunchingWithOptions:launchOptions];
  9. //自己的代码
  10. return YES;
  11. }
  12. - (void)applicationDidBecomeActive:(UIApplication *)application
  13. {
  14. [super applicationDidBecomeActive:appliction]
  15. //自己的代码
  16. }
  17. //其他生命周期函数
  18. @end

在Build iOS Project时,Unity会自动把该文件复制到Library文件里,原来的 UnityAppController在Classes文件夹里。

通过IMPL_APP_CONTROLLER_SUBCLASS知道要使用我们定制的 CustomAppController 而不是使用默认的 UnityAppController,其定义在UnityAppController.h文件中。可以看到其作用是在load的时候修改了AppControllerClassName。也即在加载UnityFramework时替换名字,这样在创建UIApplicationMain中创建的是我们新建的AppController。

  1. // Put this into mm file with your subclass implementation
  2. // pass subclass name to define
  3. #define IMPL_APP_CONTROLLER_SUBCLASS(ClassName) \
  4. @interface ClassName(OverrideAppDelegate) \
  5. { \
  6. } \
  7. +(void)load; \
  8. @end \
  9. @implementation ClassName(OverrideAppDelegate) \
  10. +(void)load \
  11. { \
  12. extern const char* AppControllerClassName; \
  13. AppControllerClassName = #ClassName; \
  14. } \
  15. @end

【参考】

UnityAppController的定制以及Unity引擎的IL2CPP机 - 简书

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/425644
推荐阅读
相关标签
  

闽ICP备14008679号