Unity Integration in React Native - By React Native Expert
banner shap banner shap

Unity Integration in React Native

Integrating Unity Games into React Native for Android

Oct 08, 2024

Save for later

Unity Integration in React Native

Introduction:

Unity is a powerful game engine widely used to create immersive 2D and 3D experiences, while React Native is a popular framework for building cross-platform mobile applications using JavaScript. Integrating Unity with React Native allows developers to enhance mobile apps with advanced 3D graphics, augmented reality (AR), and virtual reality (VR) capabilities while maintaining React Native’s native performance and UI flexibility.

In this guide, we will provide a step-by-step walkthrough of Unity integration in React Native, focusing on how to incorporate Unity’s powerful visual capabilities into your React Native app for cross-platform development. Whether you’re building apps for Android or iOS, this integration allows you to leverage Unity’s graphics engine and React Native’s cross-platform features to deliver stunning user experiences.

Why Integrate Unity with React Native?

There are several advantages to combining Unity and React Native in mobile development:

  • Rich 3D Graphics and Interactions: Unity’s 3D rendering capabilities allow developers to create complex visual elements, AR/VR experiences, and game-like interactions.
  • Cross-Platform Development: By integrating Unity into React Native, you can develop your app once and run it on both Android and iOS, reducing development time and effort.
  • Enhanced User Engagement: Apps that combine React Native’s robust UI with Unity’s 3D or AR/VR capabilities provide users with engaging and immersive experiences.
  • Native and Unity Integration: This integration allows React Native apps to keep their native functionalities while seamlessly using Unity’s advanced rendering engine.

Prerequisites:

Before you start the Unity-React Native integration process, ensure you have the following tools installed:

  • Unity Hub: Install the latest version of Unity from the Unity Hub.
  • React Native Setup: Set up your development environment for React Native, including Node.js, React Native CLI, and Android Studio.
  • Android/iOS SDK and NDK: Depending on your target platform, install the SDK and NDK required for Unity.
Step 1: Create a Unity Project
  • Create a new project in Unity Hub, selecting the 3D template or any other template.
  • In Build Settings, select Android or iOS as the platform and click Switch Platform.
  • Check the Export Project option, which allows Unity to be exported as a library that can be integrated into Android or iOS projects.
  • Build the project and generate the Unity library.
Step 2: Set up a React Native Project

Initialize a new React Native project using the command: 

				
					npx react-native init UnityReactNativeIntegration

				
			

Navigate to the Android or iOS folder inside your React Native project where you will integrate Unity.

Step 3: Import Unity as a Library in Android/iOS

1. Copy the unityLibrary folder (generated from Unity) into your React Native project’s android/app/libs folder.

2. Modify the settings. gradle file to include Unity:

				
					include ':app', ':unityLibrary'
project(':unityLibrary').projectDir = new File(rootProject.projectDir, '../app/libs/unityLibrary')

				
			

3. Open app/build.gradle and add Unity as a dependency:

				
					dependencies { 
implementation project(':unityLibrary')
}

				
			
Step 4: Modify MainActivity (Android) or AppDelegate (iOS)
In your MainActivity.java file (located in android/app/src/main/java/... ), you need to initialize Unity and manage its lifecycle.
1. Add the UnityPlayer import:
				
					import com.unity3d.player.UnityPlayer;
				
			
2. Modify the MainActivity.java to manage UnityPlayer:
				
					public class MainActivity extends ReactActivity {
    private UnityPlayer mUnityPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUnityPlayer = new UnityPlayer(this);
        setContentView(mUnityPlayer);
        mUnityPlayer.requestFocus();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mUnityPlayer.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUnityPlayer.resume();
    }

    @Override
    protected void onDestroy() {
        mUnityPlayer.quit();
        super.onDestroy();
    }
}

				
			

This ensures that Unity’s lifecycle methods (pause, resume, and destroy) are managed correctly.

Step 5: Create a Native Module for Unity

To launch Unity from React Native, we will create a native module to bridge React Native and Unity.

1. Create a new Java class called  UnityModule.java  in the android/app/src/main/java/... folder:
				
					
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class UnityModule extends ReactContextBaseJavaModule {
    public UnityModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "UnityModule";
    }

    @ReactMethod
    public void startUnityActivity() {
        Intent intent = new Intent(getCurrentActivity(), MainActivity.class);
        getCurrentActivity().startActivity(intent);
    }
}

				
			
Step 6: Call Unity from React Native

Now, from the React Native side, you can call the native module to launch Unity. Here’s how to do it:

1. In a React Native component, use NativeModules to access the Unity module:
				
					import React from 'react';
import { Button } from 'react-native';
import { NativeModules } from 'react-native';

const { UnityModule } = NativeModules;

const App = () => {
  const launchUnity = () => {
    UnityModule.startUnityActivity();
  };

  return (
    <Button title="Launch Unity" onPress={launchUnity} />
  );
};

export default App;

				
			

2. When the user presses the button, Unity will be launched and rendered inside your Android app.

Step 7: Build and Run the App

Once the setup is complete:

  • Run the React Native app on Android by executing: npx react-native run-android
  • When the app starts, click the Launch Unity button, and Unity will appear inside your React Native app.
Unity Integration in Android: Configuration Details
1. Unity Export Configuration:

⦁ Make sure to select Export Project in Unity’s Build Settings when exporting the project for Android.
⦁ Ensure that the Gradle option is selected to integrate Unity easily into Android Studio.

2. Android Studio Configuration:
  • Add Unity’s unityLibrary to your Android project’s settings and build.gradle file.
  • Ensure proper lifecycle handling of the UnityPlayer in the main activity to prevent crashes or resource leaks.
3. React Native to Unity Communication:

⦁ Utilize a native module in React Native to launch Unity. This allows you to trigger Unity experiences directly from your React Native app.

4. Managing Unity Lifecycle:
⦁ The Unity lifecycle ( onPause, onResume, and onDestroy ) needs to be managed carefully in the React Native activity to ensure that Unity behaves correctly during background/foreground transitions.
Working Example Explanation

In this example, we’ve integrated a simple Unity scene into a React Native app. The process involves:

  1. Exporting Unity as an Android library.
  2. Including Unity as a module inside the React Native Android project.
  3. Managing Unity’s lifecycle in the Android activity.
  4. Creating a bridge (via a native module) that allows React Native to trigger Unity.

This integration allows React Native apps to benefit from Unity’s advanced graphics, animations, and AR/VR features while retaining the strengths of React Native’s UI capabilities.

Advantages of Unity Integration in React Native Android Apps
  • Enhanced User Experience: Combining React Native’s UI components with Unity’s 3D/AR/VR capabilities provides a rich, interactive user experience.
  • Reusability: The Unity project can be reused across platforms (iOS and Android), ensuring that 3D and AR/VR assets are not limited to a single platform.
  • Flexibility: You can create hybrid apps where traditional mobile app functionality and Unity-driven 3D experiences coexist seamlessly.
  • Efficiency: Unity’s rendering engine makes it possible to add resource-intensive features without compromising the app’s performance.
Conclusion

Integrating Unity into React Native apps allows developers to combine 3D graphics, AR/VR experiences, and advanced visuals into mobile apps, providing a visually compelling and interactive user experience. Whether for gaming, AR applications, or high-performance visualizations, this Unity integration enables you to deliver engaging cross-platform apps without sacrificing performance or native capabilities.

Follow the steps in this guide to implement Unity integration and create next-generation mobile apps that stand out with their rich visuals and interactive features. Join us for more Interesting Information to Become React Native Experts. If you need expert assistance in building your next Shopify mobile app, feel free to contact us.

5/5 - (1 vote)