Quickstart in React Native

Integrate the ARwayKit SDK with React Native

In this quickstart guide, we will be integrating the ARwayKit SDK in React Native with the CLI.

Installed Versions

In this guide, we will be using the following versions of React, React Native, and Unity:

Download the ARwayKit SDK

Steps

  1. Download the ARwayKit SDK project from GitHub as a ZIP. You can contact us for access to the ARwayKit SDK.

Build the Project in Unity

Before adding the sample app to React Native, make sure to follow the guide Building from the Source Code first to get your Unity environment ready.

Make sure to add the Account ID and Secret Key variables to the Unity project. Follow the guide for Building from the Source Code for instructions.

Adding Folder from react-native-unity

To communicate between React Native and the Unity layer, you will need to copy the "Plugins" folder from the react-native-unity package repo and paste it into the ARwayKit SDK "Assets" folder.

After copying the folder, your project will appear as below with the nested "NativeCallProxy" files.

.
├── unity-viewer-sdk-3.1.0
│   └── Assets
│       └── Plugins
│           └── iOS
│               └── NativeCallProxy.h
│               └── NativeCallProxy.mm
│   └── Library
│   └── Logs
│   └── Packages
│   └── Project Settings
│   └── UserSettings

Creating a Blank Project in React Native

If you have already created a React Native project, you may skip the installation instructions and proceed with the next steps. Otherwise, kindly refer to the React Native documentation for installation guidelines using the "React Native CLI".

Configuration

React Native Package

In this project, the package @azesmway/react-native-unity will be used to embed the Unity SDK into React Native.

Add the following package to the React Native project:

npm install @azesmway/react-native-unity@0.4.0

Configuring Unity

The default configuration expects the Unity SDK to be in the following position in the React Native app. Move the Unity project into the below location in the React Native folder. You will need to create the folder "unity" and then paste the Unity project inside.

.
├── node_modules
├── unity
│   └── <Your Unity Project>    // Example: unity-viewer-sdk-3.1.0
├── App.tsx
├── app.json
├── babel.config.js
├── package.json
└── README.md

Android

  1. Export Unity app to [project_root]/unity/builds/android

    • Go to "File -> Build Settings" and change the platform to Android and make sure that "Export Project" is checked.

  2. Add the following lines to android/settings.gradle:

    + include ':unityLibrary'
    + project(':unityLibrary').projectDir=new File('..\\unity\\builds\\android\\unityLibrary')
  3. Add into android/build.gradle

    allprojects {
      repositories {
    +   flatDir {
    +     dirs "${project(':unityLibrary').projectDir}/libs"
    +   }
      }
    }
  4. Add into android/gradle.properties

    + unityStreamingAssets=.unity3d
  5. Add strings to android/app/src/main/res/values/strings.xml

    + <string name="game_view_content_description">Game view</string>
  6. Remove <intent-filter>...</intent-filter> from <project_name>/unity/builds/android/unityLibrary/src/main/AndroidManifest.xml to leave only integrated version.

  7. Copy the file [project_root]/unity/builds/android/local.propertiesto the folder [project_root]/android/

  8. Ensure that the minSdkVersion in android/build.gradle matches the minimum API level set in the ARwayKit Unity SDK. By default, the minimum is 24.

  9. Change the following line in unity\builds\android\unityLibrary\src\main\AndroidManifest.xml.

- <provider android:name="androidx.core.content.FileProvider" android:authorities="com.arway.sdkviewer.unitywebview.fileprovider" android:exported="false" android:grantUriPermissions="true">
+ <provider android:name="androidx.core.content.FileProvider" android:authorities="com.reactnativearwaysdk.fileprovider" android:exported="false" android:grantUriPermissions="true">

In the code above,com.arway.sdkviewer.unitywebview is replaced with com.reactnativearwaysdk. The new package name should match the namespace of your React Native package which can be found in theandroid/app/build.gradle

iOS

  1. Build the ARwayKit SDK from Unity File -> Build Settings -> Change Platform to iOS -> click Build on the bottom to the following folder in the React Native app [project_root]/unity/builds/ios

  2. After building the project, make sure that the pods are installed.

    • Go to your React Native folder, then go to ios then type pod install

  3. Add Unity-iPhone.xcodeproj to your XCode: press the right mouse button in the Left Navigator XCode -> Add Files to [project_name]... -> [project_root]/unity/builds/ios/Unity-iPhone.xcodeproj

  4. Add UnityFramework.framework to General / section Frameworks, Libraries, and Embedded Content

  5. Select Data folder and set a checkbox in the "Target Membership" section to "UnityFramework"

  6. You need to select the NativeCallProxy.h inside the Unity-iPhone/Libraries/Plugins/iOS folder of the Unity-iPhone project and change UnityFramework’s target membership from Project to Public.

    • This is required for the communication between React Native and Unity.

  7. In Build Phases remove UnityFramework.framework from Linked Binary With Libraries

  8. In Build Phases move Embedded Frameworks before Compile Sources ( drag and drop )

  9. In the React Native project, open the ios/{APP_NAME}/Info.plist and change the following key and string value to the <dict> to request authorization to the camera:

         <dict>
    +        <key>NSCameraUsageDescription</key> 
    +        <string>Used for AR Content and mapping</string> 
    +        <key>NSLocationWhenInUseUsageDescription</key> 
    +        <string>Used to attach maps with global coordinates and public map searching</string> 
    +        <key>NSMicrophoneUsageDescription</key> 
    +        <string>Used for creating audio content</string> 
    +        <key>NSPhotoLibraryAddUsageDescription</key> 
    +        <string>The app requires access to Photos to save media to it.</string> 
    +        <key>NSPhotoLibraryUsageDescription</key> 
    +        <string>The app requires access to Photos to interact with it.</string> 
         </dict>

Sample Code

Sample code to get started in React Native.

App.tsx
import React, {useRef, useEffect} from 'react';
import {View} from 'react-native';
import UnityView from '@azesmway/react-native-unity';
 
interface IMessage {
  gameObject: string;
  methodName: string;
  message: string;
}
 
const Unity = () => {
  const unityRef = useRef();
  const message: IMessage = {
    gameObject: 'GameObject',
    methodName: 'MessageRN',
    message: 'Send a message to Unity',
  };
 
  useEffect(() => {
    setTimeout(() => {
      if (unityRef && unityRef.current) {
        // @ts-ignore
        unityRef.current.postMessage(
          message.gameObject,
          message.methodName,
          message.message,
        );
      }
    }, 6000);
  }, []);
 
  return (
    <View style={{flex: 1}}>
     <UnityView
        // @ts-ignore
        ref={unityRef}
        style={{flex: 1}}
        onUnityMessage={result =>
          console.log('onUnityMessage', result.nativeEvent.message)
        }
      />
    </View>
  );
};
 
export default Unity;

Extras:

Here are some extra methods and APIs which you can implement to communicate to and from Unity.

OnEvent in Unity

Add this code to the ARwayKit Unity SDK:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine.UI;
using UnityEngine;

public class NativeAPI {
#if UNITY_IOS && !UNITY_EDITOR
  [DllImport("__Internal")]
  public static extern void sendMessageToMobileApp(string message);
#endif
}

public class ButtonBehavior : MonoBehaviour
{
  public void ButtonPressed()
  {
    if (Application.platform == RuntimePlatform.Android)
    {
      using (AndroidJavaClass jc = new AndroidJavaClass("com.azesmwayreactnativeunity.ReactNativeUnityViewManager"))
      {
        jc.CallStatic("sendMessageToMobileApp", "The button has been tapped!");
      }
    }
    else if (Application.platform == RuntimePlatform.IPhonePlayer)
    {
#if UNITY_IOS && !UNITY_EDITOR
      NativeAPI.sendMessageToMobileApp("The button has been tapped!");
#endif
    }
  }
}

Last updated