@abhishekdragon/react-native-unity-view 中文文档教程
react-native-unity-view
在 React Native 应用程序中集成 unity3d。 添加一个 React Native 组件以示统一。 适用于 iOS 和 Android。
如果您使用的 Unity 版本早于 2019.3,您只能导出到 android
Notice
这是 https://github.com/f111fei/react-native-unity-view 使其与 React Native >= 0.60 一起工作。
这个项目可能会更新也可能不会更新,这取决于它在我的工作场所的进一步使用,但是请随意分叉它
Install
yarn add @asmadsen/react-native-unity-view
Configuration
由于此项目使用从 Unity 导出的数据,因此与普通的 React Native 模块相比,您需要进行一些额外的配置。
Configuring Unity
要配置 Unity 以将导出的文件添加到您的应用程序可访问的位置,我们使用一些构建脚本。 和默认 配置要求您将 Unity 项目放置在相对于我们的应用程序的以下位置。
.
├── android
├── ios
├── unity
│ └── <Your Unity Project> // Example: Cube
├── node_modules
├── package.json
└── README.md
Add Unity Build scripts
复制 Build.cs 和 XCodePostBuild.cs 并将它们放在 unity/
如果您想将 Unity 项目放在其他地方,您必须更改以下相对于 Untiy Project
Player Settings
- Open your Unity Project
- Go to Player settings (File => Build Settings => Player Settings)
- Change
Product Name
to the name of your Xcode project. (ios/${XcodeProjectName}.xcodeproj
)
Additional changes for Android Platform
在 Other Settings
下确保 Scripting Backend
设置为 IL2CPP
,并且 ARM64
是在 Target Architectures
下检查。
在 Other Settings
下,确保未选中 Auto Graphics API
,并且列表仅按顺序包含 OpenGLES3
和 OpenGLES2
。
Additional changes for iOS Platform
在 Other Settings
下确保选中 Auto Graphics API
。
Now Unity is configured and ready
现在您可以使用 ReactNative => 导出 Unity 项目; 导出 Android
或 ReactNative => 导出 IOS
。
然后导出的工件将被放置在 android
中名为 UnityExport
的文件夹中或 ios
文件夹。
Adding UnityMessageManager Support
将 Assets 文件夹的内容添加到您的 Unity 项目中。
您必须重建才能使更改出现在 React Native 中。
Configure Native Build
Android Build
要允许项目识别 UnityExport
文件夹,您必须向 android/ 添加两行设置.gradle
。
- Add the following to the
android/build.gradle
flatDir {
dirs "${project(':UnityExport').projectDir}/libs"
}
所以它看起来像这样
// [..]
allprojects {
repositories {
// [..]
flatDir {
dirs "${project(':UnityExport').projectDir}/libs"
}
}
}
- Add these two lines to
android/settings.gradle
include ":UnityExport"
project(":UnityExport").projectDir = file("./UnityExport")
After Unity Export
iOS build
- Open your
ios/{PRODUCT_NAME}.xcworkspace
and add the exported project(ios/UnityExport/Unity-Iphone.xcodeproj
) to the workspace root
add-unity-project.png" alt="Add unity ios project to ReactNative Ios workspace">
- Select the
Unity-iPhone/Data
folder and change the Target Membership to UnityFramework
- Add
UnityFramework.framework
as a library to your Project
- Modify
main.m
#import "UnityUtils.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
InitArgs(argc, argv);
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
Use in React Native
UnityView Props
onMessage
从 Unity 接收消息
确保你有添加了 UnityMessageManager
Example:
- Send message from Unity
UnityMessageManager.Instance.SendMessageToRN("click");
- Receive message in React Native
onMessage(event) {
console.log('OnUnityMessage: ' + event.nativeEvent.message); // OnUnityMessage: click
}
render() {
return (
<View style={[styles.container]}>
<UnityView
style={style.unity}
onMessage={this.onMessage.bind(this)}
/>
</View>
);
}
onUnityMessage
[推荐]从 unity 接收 json 消息。
onUnityMessage(handler) {
console.log(handler.name); // the message name
console.log(handler.data); // the message data
setTimeout(() => {
// You can also create a callback to Unity.
handler.send('I am callback!');
}, 2000);
}
render() {
return (
<View style={[styles.container]}>
<UnityView
style={style.unity}
onUnityMessage={this.onMessage.bind(this)}
/>
</View>
);
}
UnityModule
import { UnityModule } from 'react-native-unity-view';
isReady(): Promise<boolean>
返回 unity 是否准备就绪。
createUnity(): Promise<boolean>
手动初始化 Unity。 通常 Unity 是在添加第一个视图时自动创建的。
postMessage(gameObject: string, methodName: string, message: string)
发送消息到统一。
gameObject
The Name of GameObject. Also can be a path string.methodName
Method name in GameObject instance.message
The message will post.
示例:
- Add a message handle method in
MonoBehaviour
.
public class Rotate : MonoBehaviour {
void handleMessage(string message) {
Debug.Log("onMessage:" + message);
}
}
将 Unity 组件添加到游戏对象。
发送消息使用javascript。
onToggleRotate() {
if (this.unity) {
// gameobject param also can be 'Cube'.
UnityModule.postMessage('GameObject/Cube', 'toggleRotate', 'message');
}
}
render() {
return (
<View style={[styles.container]}>
<UnityView
ref={(ref) => this.unity = ref}
style={style.unity}
/>
<Button label="Toggle Rotate" onPress={this.onToggleRotate.bind(this)} />
</View>
);
}
postMessageToUnityManager(message: string | UnityViewMessage)
向 UnityMessageManager
发送消息。
请复制UnityMessageManager.cs
到你的统一项目并首先重建。
同 postMessage('UnityMessageManager', 'onMessage', message)
推荐使用这个。
message
The message will post.
示例:
- Add a message handle method in C#.
void Awake()
{
UnityMessageManager.Instance.OnMessage += toggleRotate;
}
void onDestroy()
{
UnityMessageManager.Instance.OnMessage -= toggleRotate;
}
void toggleRotate(string message)
{
Debug.Log("onMessage:" + message);
canRotate = !canRotate;
}
- Send message use javascript.
onToggleRotate() {
UnityModule.postMessageToUnityManager('message');
}
render() {
return (
<View style={[styles.container]}>
<UnityView
ref={(ref) => this.unity = ref}
style={style.unity}
/>
<Button label="Toggle Rotate" onPress={this.onToggleRotate.bind(this)} />
</View>
);
}
addMessageListener(listener: (message: string | MessageHandler) => void): number
从 unity 接收字符串和 json 消息。
addStringMessageListener(listener: (message: string) => void): number
只接收来自 unity 的字符串消息。
addUnityMessageListener(listener: (handler: MessageHandler) => void): number
只接收来自 unity 的 json 消息。
pause()
暂停统一播放器。
resume()
恢复统一播放器。
Example Code
import React from 'react';
import { StyleSheet, Image, View, Dimensions } from 'react-native';
import UnityView from 'react-native-unity-view';
export default class App extends React.Component<Props, State> {
render() {
return (
<View style={styles.container}>
<UnityView style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }} /> : null}
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
</View>
);
}
}
react-native-unity-view
Integrate unity3d within a React Native app. Add a react native component to show unity. Works on both iOS and Android.
If you're using a Unity version older than 2019.3 you can only export to android
Notice
This is a fork of https://github.com/f111fei/react-native-unity-view to make it work with React Native >= 0.60.
This project may or may not be updated depending on the further use of it at my workplace, however feel free to fork it
Install
yarn add @asmadsen/react-native-unity-view
Configuration
Since this project uses the exported data from Unity you will have do some extra configuring than a normal React Native module.
Configuring Unity
To configure Unity to add the exported files somewhere accessible to your app we use some build scripts. And the default configuration expects that you place your Unity Project in the following position relative to our app.
.
├── android
├── ios
├── unity
│ └── <Your Unity Project> // Example: Cube
├── node_modules
├── package.json
└── README.md
Add Unity Build scripts
Copy Build.cs and XCodePostBuild.cs and place them in unity/<Your Unity Project>/Assets/Scripts/Editor/
If you want to place your Unity Project somewhere else you will have to change the following paths which is relative to the Untiy Project
Player Settings
- Open your Unity Project
- Go to Player settings (File => Build Settings => Player Settings)
- Change
Product Name
to the name of your Xcode project. (ios/${XcodeProjectName}.xcodeproj
)
Additional changes for Android Platform
Under Other Settings
make sure Scripting Backend
is set to IL2CPP
, and ARM64
is checked under Target Architectures
.
Under Other Settings
make sure Auto Graphics API
is unchecked, and the list only contains OpenGLES3
and OpenGLES2
in that order.
Additional changes for iOS Platform
Under Other Settings
make sure Auto Graphics API
is checked.
Now Unity is configured and ready
Now you can export the Unity Project using ReactNative => Export Android
or ReactNative => Export IOS
.
Then the exported artifacts will be placed in a folder called UnityExport
inside either the android
or the ios
folder.
Adding UnityMessageManager Support
Add the contents of the Assets folder, to your Unity project.
You will have to rebuild for changes to appear in React Native.
Configure Native Build
Android Build
To allow for the project to recognize the UnityExport
folder you will have to add two lines to android/settings.gradle
.
- Add the following to the
android/build.gradle
flatDir {
dirs "${project(':UnityExport').projectDir}/libs"
}
So it looks like this
// [..]
allprojects {
repositories {
// [..]
flatDir {
dirs "${project(':UnityExport').projectDir}/libs"
}
}
}
- Add these two lines to
android/settings.gradle
include ":UnityExport"
project(":UnityExport").projectDir = file("./UnityExport")
After Unity Export
iOS build
- Open your
ios/{PRODUCT_NAME}.xcworkspace
and add the exported project(ios/UnityExport/Unity-Iphone.xcodeproj
) to the workspace root
- Select the
Unity-iPhone/Data
folder and change the Target Membership to UnityFramework
- Add
UnityFramework.framework
as a library to your Project
- Modify
main.m
#import "UnityUtils.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
InitArgs(argc, argv);
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
Use in React Native
UnityView Props
onMessage
Receive message from Unity
Make sure you have added UnityMessageManager
Example:
- Send message from Unity
UnityMessageManager.Instance.SendMessageToRN("click");
- Receive message in React Native
onMessage(event) {
console.log('OnUnityMessage: ' + event.nativeEvent.message); // OnUnityMessage: click
}
render() {
return (
<View style={[styles.container]}>
<UnityView
style={style.unity}
onMessage={this.onMessage.bind(this)}
/>
</View>
);
}
onUnityMessage
[Recommended]Receive json message from unity.
onUnityMessage(handler) {
console.log(handler.name); // the message name
console.log(handler.data); // the message data
setTimeout(() => {
// You can also create a callback to Unity.
handler.send('I am callback!');
}, 2000);
}
render() {
return (
<View style={[styles.container]}>
<UnityView
style={style.unity}
onUnityMessage={this.onMessage.bind(this)}
/>
</View>
);
}
UnityModule
import { UnityModule } from 'react-native-unity-view';
isReady(): Promise<boolean>
Return whether is unity ready.
createUnity(): Promise<boolean>
Manual init the Unity. Usually Unity is auto created when the first view is added.
postMessage(gameObject: string, methodName: string, message: string)
Send message to unity.
gameObject
The Name of GameObject. Also can be a path string.methodName
Method name in GameObject instance.message
The message will post.
Example:
- Add a message handle method in
MonoBehaviour
.
public class Rotate : MonoBehaviour {
void handleMessage(string message) {
Debug.Log("onMessage:" + message);
}
}
Add Unity component to a GameObject.
Send message use javascript.
onToggleRotate() {
if (this.unity) {
// gameobject param also can be 'Cube'.
UnityModule.postMessage('GameObject/Cube', 'toggleRotate', 'message');
}
}
render() {
return (
<View style={[styles.container]}>
<UnityView
ref={(ref) => this.unity = ref}
style={style.unity}
/>
<Button label="Toggle Rotate" onPress={this.onToggleRotate.bind(this)} />
</View>
);
}
postMessageToUnityManager(message: string | UnityViewMessage)
Send message to UnityMessageManager
.
Please copy UnityMessageManager.cs
to your unity project and rebuild first.
Same to postMessage('UnityMessageManager', 'onMessage', message)
This is recommended to use.
message
The message will post.
Example:
- Add a message handle method in C#.
void Awake()
{
UnityMessageManager.Instance.OnMessage += toggleRotate;
}
void onDestroy()
{
UnityMessageManager.Instance.OnMessage -= toggleRotate;
}
void toggleRotate(string message)
{
Debug.Log("onMessage:" + message);
canRotate = !canRotate;
}
- Send message use javascript.
onToggleRotate() {
UnityModule.postMessageToUnityManager('message');
}
render() {
return (
<View style={[styles.container]}>
<UnityView
ref={(ref) => this.unity = ref}
style={style.unity}
/>
<Button label="Toggle Rotate" onPress={this.onToggleRotate.bind(this)} />
</View>
);
}
addMessageListener(listener: (message: string | MessageHandler) => void): number
Receive string and json message from unity.
addStringMessageListener(listener: (message: string) => void): number
Only receive string message from unity.
addUnityMessageListener(listener: (handler: MessageHandler) => void): number
Only receive json message from unity.
pause()
Pause the unity player.
resume()
Resume the unity player.
Example Code
import React from 'react';
import { StyleSheet, Image, View, Dimensions } from 'react-native';
import UnityView from 'react-native-unity-view';
export default class App extends React.Component<Props, State> {
render() {
return (
<View style={styles.container}>
<UnityView style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }} /> : null}
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
</View>
);
}
}