React Native系列【集成Unity】

有個項目需求,如下:

  1. 界面基本是App風(fēng)格
  2. 顯示內(nèi)容時需要用到3D模型,而且需要可操作3D對象

如果只用Unity來做,也能做出UI界面,但風(fēng)格與原生App還是有些差異,模擬實現(xiàn)起來工作量也比較大。

想著用ReactNative結(jié)合Unity來做,網(wǎng)上查找了一些資料,的確有這么做的,但有些在現(xiàn)有版本上并沒有成功,如react-native-unity-view,只到發(fā)現(xiàn)Unity官方支持原生應(yīng)用與Unity結(jié)合,但是沒有發(fā)現(xiàn)與ReactNative結(jié)合比較好的,考慮在這些人的經(jīng)驗上自己實現(xiàn)一套。

第一步:環(huán)境準(zhǔn)備

機(jī)器上nvm管理了nodejs6、nodejs8,但看到nodejs到12了,準(zhǔn)備用最新版的試試,先裝好nodejs。

yarn & react-native-cli

Chaim:workspace Chaim$ sudo npm install -g yarn react-native-cli

初始化項目

Chaim:react-native Chaim$ react-native init ReactNativeUnitylib
This will walk you through creating a new React Native project in /Users/Chaim/Documents/workspace/react-native/ReactNativeUnitylib
Using yarn v1.21.1
Installing react-native...
yarn add v1.21.1

......

info Installing required CocoaPods dependencies

  Run instructions for iOS:
    ? cd /Users/Chaim/Documents/workspace/react-native/ReactNativeUnitylib && npx react-native run-ios
    - or -
    ? Open ReactNativeUnitylib/ios/ReactNativeUnitylib.xcworkspace in Xcode or run "xed -b ios"
    ? Hit the Run button

  Run instructions for Android:
    ? Have an Android emulator running (quickest way to get started), or a device connected.
    ? cd /Users/Chaim/Documents/workspace/react-native/ReactNativeUnitylib && npx react-native run-android

這次為什么不用nvm,而直接裝呢?那是因為有些命令會直接打開命令行啟動node,給這些命令一個可用的node吧!

說明一下,編譯Xcode項目啟動的Packages Server, 是在Build Phases中腳本設(shè)置的。

第二步:原生與Unity結(jié)合

初始項目修改下簽名,正常就能運(yùn)行起來,這步是將RN生成的項目與Unity結(jié)合,先在原生代碼中顯示Unity內(nèi)容。

根據(jù)官方示例生成的UnityProject項目,build ios版本。

添加UnityFramwork.framework時XCode就崩潰,解決了很長時間,最終通過在Build Phases中拷貝framework的方法解決。

原生顯示不管RN時比較簡單,如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [self initRNandUnity];

  UIWindow* unityWindow = [[[self ufw] appController] window];
  self.window = unityWindow;
  [self.window makeKeyAndVisible];

  return YES;
}

- (bool)unityIsInitialized { return [self ufw] && [[self ufw] appController]; }

// Method to initialize RN and Unity
- (void)initRNandUnity
{
  /////////////////
  // Unity bundle loading
  if([self unityIsInitialized]) { // safeguard for unity bundle dynamic load/unload example (not in use)
//    showAlert(@"Unity already initialized", @"Unload Unity first");
    return;
  }
  [self setUfw: UnityFrameworkLoad()];
  // Set UnityFramework target for Unity-iPhone/Data folder to make Data part of a UnityFramework.framework and uncomment call to setDataBundleId
  // ODR is not supported in this case, ( if you need embedded and ODR you need to copy data )
  [[self ufw] setDataBundleId: "com.unity3d.framework"];
//  [[self ufw] registerFrameworkListener: self];
//  [NSClassFromString(@"FrameworkLibAPI") registerAPIforNativeCalls:self];
  [[self ufw] runEmbeddedWithArgc: gArgc argv: gArgv appLaunchOpts: appLaunchOpts];
  
  self.unityView = [[[self ufw] appController] rootView]; // set view to root
}

將Unity window直接賦值給self.window顯示即可。

同時還要注意下全局變量,在main.mm中定義,在AppDelegate.mm中使用,如下:

// keep arg for unity init from non main
extern int gArgc;
extern char** gArgv;

否則runEmbeddedWithArgc()又會異常。

處理這個時間完全超出預(yù)計,本來以為加上RN控件一天搞定,結(jié)果估計還得一天...

第三步、Unity上顯示RN

可以按此處一樣,在Unity上顯示RN控件:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [self initRNandUnity];
  self.window = [[[self ufw] appController] window];

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"ReactNativeUnitylib"
                                            initialProperties:nil];

//  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  rootView.frame = CGRectMake(0, 0, self.unityView.frame.size.width, 400); // React
  rootView.backgroundColor = UIColor.clearColor; // transparent view on ios, only items set in react can be seen
  [self.unityView addSubview:rootView]; // to-do: adding an animation

  [self.window makeKeyAndVisible];

  return YES;
}

當(dāng)然也可以Unity是一個單獨的窗口,顯示在RN窗口前面,如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"ReactNativeUnitylib"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

   [self initRNandUnity];
   UIWindow* unityWindow = [[[self ufw] appController] window];
   CGRect viewRect = CGRectMake(0, 0, self.window.rootViewController.view.frame.size.width, 400);
   UIView* unityView = [[[self ufw] appController] rootView];
   unityView.frame = viewRect;
   [unityWindow makeKeyAndVisible];

   return YES;
}

但是發(fā)現(xiàn)無論怎么設(shè)置Unity窗口高度,Unity都是全屏!這樣怎么才能把Unity做為一個組件加載呢?麻煩了!

查找了些資料,發(fā)現(xiàn)在Untiy啟動時設(shè)置frame尺寸可能可以,可以用子類化來做,先簡單直接改Unity啟動代碼吧!

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
  ......

    CGRect viewRect = CGRectMake(0, 0, 300, 400);
    _window         = [[UIWindow alloc] initWithFrame: viewRect];
//  _window         = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
    _unityView      = [self createUnityView];

    ......
}
image.png

還真是可以,下一步當(dāng)做組件來顯示看來有戲了!

~好吧,我考慮復(fù)雜了,一直在改rootView的尺寸,其實應(yīng)該修改window尺寸即可修改unity窗口尺寸,如下:

   UIWindow* unityWindow = [[[self ufw] appController] window];
   CGRect viewRect = CGRectMake(100, 100, 400, 400);
  unityWindow.frame = viewRect;

第四步、實現(xiàn)ReactNative的Unity組件

先參考ReactNative原生UI組件實現(xiàn)一個原生組件。

RCTUnityView.h

//
//  RCTUnityView.h
//  ReactNativeUnitylib
//
//  Created by Chaim on 2019/12/23.
//  Copyright ? 2019 Facebook. All rights reserved.
//

#ifndef RCTUnityView_h
#define RCTUnityView_h

#import <UIKit/UIKit.h>
 
@interface RCTUnityView : UIView
 
@property (nonatomic, strong) UIView* uView;
 
@end

#endif /* RCTUnityView_h */

RCTUnityView.mm

//
//  RCTUnityView.m
//  ReactNativeUnitylib
//
//  Created by Chaim on 2019/12/23.
//  Copyright ? 2019 Facebook. All rights reserved.
//

#import "RCTUnityView.h"
#import "AppDelegate.h"

@implementation RCTUnityView
 
-(id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self){

//    UIView *cellView = [[UIView alloc] init];
//    cellView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:0.0f blue:0.0f alpha:1];
    AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    UIView* unityView = [[[appDelegate ufw] appController] window];
    
    self.uView = (UIView*)unityView;
  }
  return self;
}
 
-(void)layoutSubviews
{
  [super layoutSubviews];
  [self.uView removeFromSuperview];
  self.uView.frame = self.bounds;
  [self insertSubview:self.uView atIndex:0];
  [self.uView setNeedsLayout];
}
 
@end

RCTUnityViewManager.h

//
//  RCTUnityViewManager.h
//  ReactNativeUnitylib
//
//  Created by Chaim on 2019/12/23.
//  Copyright ? 2019 Facebook. All rights reserved.
//

#ifndef RCTUnityViewManager_h
#define RCTUnityViewManager_h

#import <React/RCTViewManager.h>

@interface RCTUnityViewManager : RCTViewManager
 
@end

#endif /* RCTUnityViewManager_h */

RCTUnityViewManager.m

//
//  RCTUnityViewManager.h
//  ReactNativeUnitylib
//
//  Created by Chaim on 2019/12/23.
//  Copyright ? 2019 Facebook. All rights reserved.
//

#ifndef RCTUnityViewManager_h
#define RCTUnityViewManager_h

#import <React/RCTViewManager.h>

@interface RCTUnityViewManager : RCTViewManager
 
@end

#endif /* RCTUnityViewManager_h */

RCTUnityView.js

import { requireNativeComponent } from 'react-native';

export default requireNativeComponent('RCTUnityView');

App.js

import RCTUnityView from './RCTUnityView.js';

<ScrollView>
          <RCTUnityView style={{left:50, top: 0, width: 300, height: 500 }} />
</ScrollView>

最終結(jié)果如下,和其它控件一起,也可以滾動:

image.png

非常感謝此文的指引!

參考

https://forum.unity.com/threads/integration-unity-as-a-library-in-native-ios-app.685219

https://github.com/CGS-Canada/react-native-unity

https://docs.unity3d.com/2020.1/Documentation/Manual/UnityasaLibrary-iOS.html

https://blog.mutoo.im/2015/09/make-subclass-from-unityappcontroller/

https://stackoverflow.com/questions/42508476/can-you-have-more-than-one-subclass-of-unityappcontroller

https://twnkls.com/blogs/howto-native-ios-plugins-for-unity3d/

解決Embed UnityFramework.framework崩潰問題

1:首先需要在“ 構(gòu)建階段”選項卡下添加“ 新建副本文件”階段。


image.png

2: Second change the name of the added phase to Embed Frameworks


image.png

3: Change the destination to Frameworks.


image.png

4: Add the framework for which the error occurred.


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容