### Initialize Unity Context in React
Source: https://react-unity-webgl.dev/docs/8.x.x/getting-started
Demonstrates how to import and initialize the Unity and Unity Context classes from the 'react-unity-webgl' module. The Unity Context object holds configuration and event listeners for the Unity build. This setup is essential for rendering a Unity application within a React component.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function App() {
return ;
}
```
--------------------------------
### Basic React Unity WebGL Integration
Source: https://react-unity-webgl.dev/docs/9.x.x/getting-started/hello-world
This snippet shows the fundamental setup for integrating a Unity WebGL application into a React project. It imports the necessary 'Unity' component and 'useUnityContext' hook, configures the Unity context with build file paths, and renders the Unity application. Ensure your Unity build files (loader, data, framework, wasm) are correctly placed.
```jsx
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return ;
}
```
--------------------------------
### Install Local React Unity WebGL Package (npm)
Source: https://react-unity-webgl.dev/docs/7.x.x/contribution-and-development
This snippet demonstrates how to pack and install a local version of the 'react-unity-webgl' package into another application. It involves navigating to the package directory, packing it into a .tgz file, and then installing that file in the target application. This method is recommended over 'npm link' for React-based libraries.
```bash
cd ../react-unity-webgl/
npm pack
cd ../yourapp
npm remove react-unity-webgl
npm install ../react-unity-webgl/react-unity-webgl-x.y.z.tgz
```
--------------------------------
### Install Local React Unity WebGL Package
Source: https://react-unity-webgl.dev/docs/8.x.x/contribution-and-development
This sequence of commands demonstrates how to pack the React Unity WebGL library locally and install it into a separate application for iterative testing. It ensures compatibility with the production build process by avoiding symlink-based installations.
```shell
cd ../react-unity-webgl/
npm pack
cd ../your-app
npm remove react-unity-webgl
npm install ../react-unity-webgl/react-unity-webgl-x.y.z.tgz
```
--------------------------------
### Install React Unity WebGL v5 with npm
Source: https://react-unity-webgl.dev/docs/5.x.x/installation
This command installs version 5.x of the React Unity WebGL library using npm. Ensure the installed version is compatible with your Unity project version by checking the GitHub releases.
```bash
npm install react-unity-webgl@5.x
```
--------------------------------
### Implement Unity Loading Overlay in React
Source: https://react-unity-webgl.dev/docs/9.x.x/advanced-examples/loading-overlay
This React component demonstrates how to render a Unity application and display a custom loading overlay while it's initializing. It uses the `useUnityContext` hook to get the loading progress and conditionally renders the overlay based on the `isLoaded` state. The overlay shows the loading percentage.
```jsx
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, isLoaded, loadingProgression } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
// We'll round the loading progression to a whole number to represent the
// percentage of the Unity Application that has loaded.
const loadingPercentage = Math.round(loadingProgression * 100);
return (
{isLoaded === false && (
// We'll conditionally render the loading overlay if the Unity
// Application is not loaded.
Loading... ({loadingPercentage}%)
)}
);
}
```
--------------------------------
### Example Usage: Displaying FPS
Source: https://react-unity-webgl.dev/docs/api/use-unity-metrics-info
A complete React component example demonstrating the integration of Unity, useUnityContext, and useUnityMetricsInfo to display the FPS of a Unity WebGL application. It includes necessary imports and Unity provider configuration.
```jsx
import React, { Fragment } from "react";
import { Unity, useUnityContext, useUnityMetricsInfo } from "react-unity-webgl";
function App() {
const { unityProvider, getMetricsInfo } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
const { fps } = useUnityMetricsInfo(getMetricsInfo, {
interval: 1000 / 60,
});
return (
FPS: {fps}
);
}
```
--------------------------------
### Example Fullscreen Implementation in React App
Source: https://react-unity-webgl.dev/docs/9.x.x/api/request-fullscreen
A complete example of integrating fullscreen functionality into a React application using React Unity WebGL. It sets up the Unity context, provides a button to trigger fullscreen mode, and renders the Unity application.
```jsx
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, requestFullscreen } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function handleClickEnterFullscreen() {
requestFullscreen(true);
}
return (
);
}
```
--------------------------------
### Install React Unity WebGL v7 using npm
Source: https://react-unity-webgl.dev/docs/7.x.x/installation
This command installs version 7 of the react-unity-webgl package using npm. Ensure you download the release matching your Unity version for compatibility.
```bash
npm install react-unity-webgl@7
```
--------------------------------
### Import and Render Unity Component in React
Source: https://react-unity-webgl.dev/docs/6.x.x/getting-started
This snippet demonstrates how to import the default Unity class from the react-unity-webgl library and render it within a React component. It requires specifying the public path to your Unity build's JSON file and the UnityLoader JavaScript file.
```javascript
import React from "react";
import Unity from "react-unity-webgl";
export class App extends React.Component {
render() {
return (
);
}
}
```
--------------------------------
### Example: Get Unity Canvas Reference in React with JavaScript
Source: https://react-unity-webgl.dev/docs/8.x.x/api/canvas-reference
Demonstrates a basic implementation in React using JavaScript to get a reference to the Unity Canvas. It initializes a UnityContext and uses the `useEffect` hook to register a listener for the 'canvas' event. Once the canvas is available, it retrieves the WebGL rendering context. This requires the `react-unity-webgl` package and correctly configured Unity build paths.
```javascript
import React, { useEffect } from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function App() {
useEffect(function () {
unityContext.on("canvas", function (canvas) {
canvas.getContext("webgl");
});
}, []);
return ;
}
```
--------------------------------
### React Unity WebGL: Display FPS using getMetricsInfo
Source: https://react-unity-webgl.dev/docs/api/get-metrics-info
A complete React component example that utilizes `useUnityContext` to initialize a Unity application and `getMetricsInfo` to display the current frames per second (FPS) when a button is clicked. It handles cases where metrics might not be available.
```javascript
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, getMetricsInfo } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function handleClickCheckFps() {
const metricsInfo = getMetricsInfo();
if (metricsInfo) {
console.log("FPS:", metricsInfo.fps);
} else {
console.warn("Metrics info is not available.");
}
}
return (
);
}
```
--------------------------------
### JSLib Example for Communication
Source: https://react-unity-webgl.dev/docs/6.x.x/api/unity-to-react-communication
Example of a JSLib file that binds a Unity-called function to a React callback.
```APIDOC
## JSLib Binding Example
### Description
This example demonstrates how to create a JSLib file (`MyPlugin.jslib`) to make a React callback function available to Unity.
### Method
`mergeInto(LibraryManager.library, { ... });`
### Endpoint
`Assets/Plugins/WebGL/MyPlugin.jslib`
### Parameters
None
### Request Example
```javascript
mergeInto(LibraryManager.library, {
OpenMenu: function (menuId) {
ReactUnityWebGL.OpenMenu(menuId);
},
});
```
### Response
#### Success Response (void)
This JSLib binding does not return a direct value to Unity. It facilitates the call to the React callback.
#### Response Example
N/A
```
--------------------------------
### Full Example: Taking and Displaying a Screenshot in React
Source: https://react-unity-webgl.dev/docs/9.x.x/api/take-screenshot
A complete React component example demonstrating the integration of React Unity WebGL. It includes initializing the Unity context with 'preserveDrawingBuffer' enabled, destructuring 'takeScreenshot', and providing a button to capture and open the screenshot in a new tab.
```javascript
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, takeScreenshot } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
webglContextAttributes: {
preserveDrawingBuffer: true,
},
});
function handleClickTakeScreenshot() {
const dataUrl = takeScreenshot("image/jpg", 0.5);
window.open(dataUrl, "_blank");
}
return (
);
}
```
--------------------------------
### React Example: Setting Streaming Assets URL
Source: https://react-unity-webgl.dev/docs/api/streaming-assets
Demonstrates how to initialize the Unity context in a React application and set the 'streamingAssetsUrl' to a specific directory. This ensures that the Unity application can correctly locate its streaming assets.
```javascript
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
streamingAssetsUrl: "streamingassets",
});
return ;
}
```
--------------------------------
### Render Unity App in React (React)
Source: https://react-unity-webgl.dev/docs/9.x.x/quick-start/simple-example
This snippet demonstrates how to render a Unity application within a React component using the react-unity-webgl library. It requires the Unity component and the useUnityContext hook. The example specifies the URLs for the Unity build assets and sets inline styles for the canvas to control its dimensions and aspect ratio.
```jsx
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return (
);
}
```
--------------------------------
### React Unity WebGL Basic Implementation with Meta Data
Source: https://react-unity-webgl.dev/docs/8.x.x/api/application-meta-data
Demonstrates a fundamental React component setup for integrating a Unity application. It initializes Unity with necessary build files and configures essential application metadata like product name and version.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
productName: "My Game",
productVersion: "1.0.0",
companyName: "El Raccoone",
});
function App() {
return ;
}
```
--------------------------------
### React Unity WebGL Example Usage with WebGLContextAttributes (React/JavaScript)
Source: https://react-unity-webgl.dev/docs/api/webgl-rendering-context
Demonstrates how to configure and pass WebGLContextAttributes to the UnityContext in a React application using react-unity-webgl. This example showcases setting various attributes to customize the WebGL rendering environment.
```javascript
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
webglContextAttributes: {
alpha: true,
antialias: true,
depth: true,
failIfMajorPerformanceCaveat: true,
powerPreference: "high-performance",
premultipliedAlpha: true,
preserveDrawingBuffer: true,
stencil: true,
desynchronized: true,
xrCompatible: true,
},
});
return ;
}
```
--------------------------------
### React Example for Setting Streaming Assets URL
Source: https://react-unity-webgl.dev/docs/9.x.x/api/streaming-assets
Demonstrates how to configure the 'streamingAssetsUrl' within the `useUnityContext` hook in a React application. This example sets the base URL for streaming assets to the 'streamingassets' directory, enabling the Unity application to locate these files.
```javascript
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
streamingAssetsUrl: "streamingassets",
});
return ;
}
```
--------------------------------
### Example Usage: Unload Unity App Before Navigation
Source: https://react-unity-webgl.dev/docs/9.x.x/api/unload
Provides a full example of integrating the `unload` function into a React component. It sets up the Unity context, includes a button that, when clicked, first unloads the Unity application using `await unload()`, and then allows for navigation to another page. This ensures memory is freed before leaving the current view.
```javascript
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, unload } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
async function handleClickBack() {
await unload();
// Ready to navigate to another page.
}
return (
);
}
```
--------------------------------
### Style Unity Loading Overlay and Container in CSS
Source: https://react-unity-webgl.dev/docs/9.x.x/advanced-examples/loading-overlay
These CSS rules define the styling for the container that holds the Unity application and the loading overlay. The container is set to a fixed size, and the overlay is positioned absolutely to cover it entirely, with centered text. The Unity application itself is styled to fill its container.
```css
.container {
position: relative;
/* The container determains the size. */
width: 800px;
height: 600px;
}
.container > .loading-overlay {
/* We'll render the overlay on top of the Unity Application. */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: grey;
/* We'll set the following Flex properties in order to center the text. */
display: flex;
justify-content: center;
align-items: center;
}
.container > .unity {
/* The Unity Application matches it size to the container. */
width: 100%;
height: 100%;
}
```
--------------------------------
### Example Usage: Hiding Unity App While Loading
Source: https://react-unity-webgl.dev/docs/api/is-loaded
Provides a complete React component example (`App.jsx`) that uses `useUnityContext` to manage the `isLoaded` state. It conditionally sets the visibility of the `Unity` component, hiding it until the application is fully loaded to prevent premature interaction.
```javascript
import React from "";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, isLoaded } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return (
);
}
```
--------------------------------
### React Unity WebGL Initialization with Debug Symbols
Source: https://react-unity-webgl.dev/docs/8.x.x/api/debugging-symbols
An example of initializing the Unity context in a React application. It demonstrates how to set the 'symbolsUrl' to a specific file path for debugging purposes. This requires the 'react-unity-webgl' library.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
symbolsUrl: "build/debug-symbols.json",
});
function App() {
return ;
}
```
--------------------------------
### Example: Setting Application Meta Data in React Unity WebGL
Source: https://react-unity-webgl.dev/docs/api/meta-data
Demonstrates how to initialize the Unity context with application meta data in a React application. It uses the `useUnityContext` hook from 'react-unity-webgl' and passes product name, version, and company name as configuration options.
```javascript
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
productName: "My Game",
productVersion: "1.0.0",
companyName: "Developer",
});
return ;
}
```
--------------------------------
### Unity to JavaScript Data Conversion Example (JavaScript)
Source: https://react-unity-webgl.dev/docs/main-concepts/data-conversion
Demonstrates merging C# methods into the Unity library to make them available in JavaScript. This example showcases how to handle string and float array conversions using Emscripten helper functions like UTF8ToString and HEAPF32. These converted values are then dispatched to a React Unity event handler.
```javascript
mergeInto(LibraryManager.library, {
GameOver: function () {
window.UnityEvent("GameOver");
},
NextWave: function (waveNumberValue) {
window.dispatchReactUnityEvent("NextWave", waveNumberValue);
},
ShowPopup: function (textStringPointer) {
window.dispatchReactUnityEvent(
"ShowPopup",
UTF8ToString(textStringPointer)
);
},
SubmitScores: function (scoresFloatArrayPointer, arraySize) {
var scores = [];
for (var i = 0; i < arraySize;
i++
)
scores.push(HEAPF32[(scoresFloatArrayPointer >> 2) + i]);
window.dispatchReactUnityEvent("SubmitScores", scores);
},
});
```
--------------------------------
### Example Usage: Stop Unity Application Button
Source: https://react-unity-webgl.dev/docs/api/unload
This comprehensive example shows a basic React component that includes a Unity application and a button to stop it. When the 'Stop' button is clicked, the `handleClickStop` function is invoked, which in turn calls the `unload` function to unload the Unity application from memory. This prevents memory leaks in multi-page scenarios.
```jsx
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, unload } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
async function handleClickStop() {
await unload();
}
return (
);
}
```
--------------------------------
### Example Usage of Unsafe Unity Instance Access
Source: https://react-unity-webgl.dev/docs/9.x.x/api/unsafe-unity-instance
Demonstrates how to access the Unity Instance directly using the useUnityContext hook and bind it to the window object for external script access. This requires react and react-unity-webgl.
```jsx
import React, { useEffect } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, UNSAFE__unityInstance } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
useEffect(
() => (window.unityInstance = UNSAFE__unityInstance),
[UNSAFE__unityInstance]
);
return ;
}
```
--------------------------------
### Displaying Loading Progression as Percentage (React)
Source: https://react-unity-webgl.dev/docs/api/loading-progression
Shows a basic React example of using the `loadingProgression` value to display the loading progress as a percentage. The `Math.round` function is used for cleaner output.
```javascript
import React, {
Fragment
} from "react";
import {
Unity,
useUnityContext
} from "react-unity-webgl";
function App() {
const { unityProvider,
loadingProgression
} = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return (
);
}
```
--------------------------------
### React Component for Fullscreen Toggle (JavaScript)
Source: https://react-unity-webgl.dev/docs/8.x.x/api/set-fullscreen
An example React component demonstrating how to integrate fullscreen functionality. It utilizes the `react-unity-webgl` library and attaches a button to trigger the fullscreen mode via the `unityContext.setFullscreen` method.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function App() {
function handleOnClickFullscreen() {
unityContext.setFullscreen(true);
}
return (
);
}
```
--------------------------------
### C# Script to Call React Function
Source: https://react-unity-webgl.dev/docs/6.x.x/api/unity-to-react-communication
Example of a C# script in Unity that exposes a function to call a registered React listener.
```APIDOC
## C# Script for React Communication
### Description
This C# script in Unity shows how to call a JavaScript function (previously registered with `RegisterExternalListener`) in React using `DllImport`.
### Method
`public void OpenReactMenuById (string menuId)`
### Endpoint
Any C# script within the Unity project.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* **menuId** (string) - The identifier for the menu to open, passed to the React callback.
### Request Example
```csharp
using UnityEngine;
using System.Runtime.InteropServices;
public class MenuController: MonoBehaviour {
[DllImport("__Internal")]
private static extern void OpenMenu (string menuId);
public void OpenReactMenuById (string menuId) {
OpenMenu (menuId);
}
}
```
### Response
#### Success Response (void)
This method is used to initiate a call to React and does not return a value directly to the C# script.
#### Response Example
N/A
```
--------------------------------
### React useEffect Example for Unloading Unity Instance
Source: https://react-unity-webgl.dev/docs/9.x.x/api/unsafe-detach-unmount-immediate
An example demonstrating how to use the UNSAFE__detachAndUnloadImmediate function within a React component's useEffect hook. This ensures the Unity instance is detached and unloaded immediately when the component unmounts, preventing potential memory leaks.
```javascript
import React, { useEffect } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, UNSAFE__detachAndUnloadImmediate } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
useEffect(() => {
return () => {
UNSAFE__detachAndUnloadImmediate();
};
}, []);
return ;
}
```
--------------------------------
### React Component for Unity App with Loading Overlay
Source: https://react-unity-webgl.dev/docs/advanced-examples/loading-overlay
This React component renders a Unity application and displays a loading overlay with progress percentage while the application is initializing. It uses the 'useUnityContext' hook from 'react-unity-webgl' to manage the Unity instance and its loading state. The overlay is conditionally rendered based on the 'isLoaded' flag.
```jsx
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, isLoaded, loadingProgression } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
// We'll round the loading progression to a whole number to represent the
// percentage of the Unity Application that has loaded.
const loadingPercentage = Math.round(loadingProgression * 100);
return (
{isLoaded === false && (
// We'll conditionally render the loading overlay if the Unity
// Application is not loaded.
Loading... ({loadingPercentage}%)
)}
);
}
```
--------------------------------
### Implement Unity Context with WebGL Attributes in React
Source: https://react-unity-webgl.dev/docs/8.x.x/api/webgl-rendering-context
Shows a basic React component setup using `react-unity-webgl`. It demonstrates how to instantiate `UnityContext` with specific `webGLContextAttributes` to customize the WebGL rendering environment for the Unity application. This includes setting various boolean flags and power preference.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
webGLContextAttributes: {
alpha: true,
antialias: true,
depth: true,
failIfMajorPerformanceCaveat: true,
powerPreference: "high-performance",
premultipliedAlpha: true,
preserveDrawingBuffer: true,
stencil: true,
desynchronized: true,
xrCompatible: true,
},
});
function App() {
return ;
}
```
--------------------------------
### Unity C#: Handling Messages from React
Source: https://react-unity-webgl.dev/docs/9.x.x/api/send-message
Provides an example of a C# script for Unity that can receive messages from a React application. This script defines a public method 'SpawnEnemies' that accepts an integer parameter and logs a message to the Unity console.
```csharp
using UnityEngine;
public class EnemyController : MonoBehaviour {
public void SpawnEnemies (int amount) {
Debug.Log ($"Spawning {amount} enemies!");
}
}
```
--------------------------------
### React: Manage Unity Game Visibility on Load
Source: https://react-unity-webgl.dev/docs/8.x.x/api/on-loaded
An example implementation in React using the 'react-unity-webgl' library. It demonstrates how to conditionally set the Unity game's visibility based on whether the 'loaded' event has been triggered. It requires 'react' and 'react-unity-webgl' as dependencies.
```javascript
import React, { useState, useEffect } from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function App() {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(function () {
unityContext.on("loaded", function () {
setIsLoaded(true);
});
}, []);
return (
);
}
```
--------------------------------
### Render Unity Player with Unity Content
Source: https://react-unity-webgl.dev/docs/7.x.x/api/unity-component
Renders a Unity Player component using the provided Unity Content object. This is the basic setup for integrating a Unity application into a React component. No external dependencies are required beyond the React Unity WebGL library.
```javascript
```
--------------------------------
### Invoke takeScreenshot Function with Image Type and Quality
Source: https://react-unity-webgl.dev/docs/9.x.x/api/take-screenshot
An example of how to call the 'takeScreenshot' function, passing 'image/jpg' as the data type and 1.0 as the quality. The returned data URL can then be used, for instance, to open the image in a new tab.
```javascript
function handleClick() {
const dataUrl = takeScreenshot("image/jpg", 1.0);
}
return ;
```
--------------------------------
### React Unity WebGL - Event Handling
Source: https://react-unity-webgl.dev/docs/9.x.x/api/event-system
This section details how to manage communication from Unity to React using event listeners. It covers registering, removing, and dispatching events, along with examples of binding callbacks to state and functions.
```APIDOC
## Communication from Unity to React
This API allows you to receive messages sent from the Unity game within your React application.
### Core Functions
* `addEventListener(eventName: string, callback: (...parameters: ReactUnityEventParameterType[]) => void): void`
* `removeEventListener(eventName: string, callback: (...parameters: ReactUnityEventParameterType[]) => void): void`
* `dispatchReactUnityEvent(eventName: string, ...parameters: ReactUnityEventParameterType[]): void`
### Type Definition
* `ReactUnityEventParameter = string | number | undefined`
### Implementation Details
Communication from Unity to React is handled globally. Event listeners with the same name will be invoked on all Unity Context instances.
Simple numeric types can be passed directly. For other types like strings, you might need helper functions like `Pointerstringify`.
### Registering Event Listeners
To begin, destructure `addEventListener` and `removeEventListener` from `useUnityContext()`.
```javascript
const { addEventListener, removeEventListener } = useUnityContext();
```
#### Binding Callback to State
When the callback parameters match state parameters, you can bind the callback directly to update the state.
```javascript
import React, { useState, useEffect } from 'react';
import { useUnityContext } from 'react-unity-webgl';
function MyComponent() {
const { addEventListener, removeEventListener } = useUnityContext();
const [score, setScore] = useState();
useEffect(() => {
addEventListener("SetScore", setScore);
return () => {
removeEventListener("SetScore", setScore);
};
}, [addEventListener, removeEventListener, setScore]);
// ... render component
}
```
#### Binding Callback to a Function
If the callback parameters do not match state parameters, bind the callback to a function to perform specific actions.
```javascript
import React, { useCallback, useEffect } from 'react';
import { useUnityContext } from 'react-unity-webgl';
function MyComponent() {
const { addEventListener, removeEventListener } = useUnityContext();
const handleSetScore = useCallback((score) => {
// Do something with the score
console.log("Received score:", score);
}, []);
useEffect(() => {
addEventListener("SetScore", handleSetScore);
return () => {
removeEventListener("SetScore", handleSetScore);
};
}, [addEventListener, removeEventListener, handleSetScore]);
// ... render component
}
```
**Note:** Always bind your callback using an effect hook in function components to ensure proper cleanup when the component unmounts or re-renders.
```
--------------------------------
### Implement Streaming Assets URL in React (JavaScript)
Source: https://react-unity-webgl.dev/docs/8.x.x/api/streaming-assets-url
This example demonstrates how to implement the 'streamingAssetsUrl' configuration within a React component using the 'react-unity-webgl' library. It shows setting the 'streamingAssetsUrl' to a specific directory ('streamingassets') when initializing the UnityContext.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
streamingAssetsUrl: "streamingassets",
});
function App() {
return ;
}
```
--------------------------------
### React Implementation to Send Message
Source: https://react-unity-webgl.dev/docs/8.x.x/api/communication-from-react-to-unity
This React example demonstrates sending a message to Unity when a button is clicked. It imports necessary components from 'react-unity-webgl', initializes a Unity context, and defines a function to call `unityContext.send`. This function targets a GameObject named 'GameController' to execute the 'SpawnEnemies' method with an integer parameter.
```javascript
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
function App() {
function spawnEnemies() {
unityContext.send("GameController", "SpawnEnemies", 100);
}
return (
);
}
```
--------------------------------
### Define JSLib Function for React Communication (React Unity WebGL)
Source: https://react-unity-webgl.dev/docs/6.x.x/api/unity-to-react-communication
Shows how to create a JavaScript file (JSLib) to bind communication between Unity and React. The `ReactUnityWebGL` object is used to access the listener registered in React. This example defines an `OpenMenu` function in the JSLib that calls the `OpenMenu` function in React.
```javascript
mergeInto(LibraryManager.library, {
OpenMenu: function (menuId) {
ReactUnityWebGL.OpenMenu(menuId);
},
});
```
--------------------------------
### Handle Unity Player Load Event in JavaScript
Source: https://react-unity-webgl.dev/docs/7.x.x/api/on-loaded
This JavaScript example demonstrates how to use the 'loaded' event from React Unity WebGL to detect when the Unity player has finished loading. It allows for actions like hiding loading overlays. The code requires the 'react-unity-webgl' library.
```javascript
import React from "react";
import Unity, { UnityContent } from "react-unity-webgl";
export class App extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true };
this.unityContent = new UnityContent(
"MyGame/Build.json",
"MyGame/UnityLoader.js"
);
// Create a new listener for our on loaded Event.
// When the unity player is loaded, the event will
// fire.
this.unityContent.on("loaded", () => {
// Now we can for example hide the loading overlay.
this.setState({
isLoading: false,
});
});
}
render() {
// Finally render the Unity component and pass
// the Unity content through the props. Along with
// a text that shows wether the player is loading.
return (
{this.state.isLoading === true &&
{"Loading..."}
}
);
}
}
```
--------------------------------
### Implement JavaScript to UnityScript Type Conversions
Source: https://react-unity-webgl.dev/docs/8.x.x/concepts/javascript-to-unityscript-types
This example demonstrates how to merge JavaScript functions into the Unity library to make them available in C#. It covers handling string conversions using UTF8ToString and float array conversions using HEAPF32, showcasing basic data type passing and event dispatching.
```javascript
mergeInto(LibraryManager.library, {
GameOver: function () {
window.UnityEvent("GameOver");
},
NextWave: function (waveNumberValue) {
window.dispatchReactUnityEvent("NextWave", waveNumberValue);
},
ShowPopup: function (textStringPointer) {
window.dispatchReactUnityEvent(
"ShowPopup",
UTF8ToString(textStringPointer)
);
},
SubmitScores: function (scoresFloatArrayPointer, arraySize) {
var scores = [];
for (var i = 0; i < arraySize; i++)
scores.push(HEAPF32[(scoresFloatArrayPointer >> 2) + i]);
window.dispatchReactUnityEvent("SubmitScores", scores);
},
});
```
--------------------------------
### HTML Structure for React Unity WebGL v5
Source: https://react-unity-webgl.dev/docs/5.x.x/api/html-example
This HTML structure is essential for setting up a React Unity WebGL project using version 5. It includes the basic HTML boilerplate, a div with the ID 'app' where the React application will mount, and links to the 'UnityLoader.js' and the compiled 'bundle.js' scripts. Ensure these scripts are correctly linked for the application to load properly.
```html
My Unity Game
```
--------------------------------
### Get Unity Canvas Reference using useRef Hook (React)
Source: https://react-unity-webgl.dev/docs/9.x.x/api/canvas-ref
This snippet demonstrates how to use the `useRef` hook in React to get a reference to the Unity Application's Canvas element. This reference can then be used to interact with the canvas, such as focusing it. It's recommended to use built-in Unity Context API functions when possible.
```javascript
import React, { useRef, Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
const canvasRef = useRef(null);
function focusCanvas() {
if (canvasRef.current) {
canvasRef.current.focus();
}
}
return (
);
}
```
--------------------------------
### Create Unity Content Object
Source: https://react-unity-webgl.dev/docs/7.x.x/api/unity-content
Initializes a Unity Content object by specifying the paths to the Unity build's configuration JSON and JavaScript loader file. This is a prerequisite for rendering Unity content within the React application.
```javascript
let unityContent = new UnityContent({
"MyGame/Build.json",
"MyGame/UnityLoader.js"
});
```
--------------------------------
### Initialize Unity Content with Configuration
Source: https://react-unity-webgl.dev/docs/7.x.x/api/unity-config
Demonstrates the basic structure for initializing a Unity Content object with optional configuration parameters. This includes paths to the build JSON and JavaScript loader, along with an empty configuration object.
```javascript
let unityContent = new UnityContent(
"MyGame/Build.json",
"MyGame/UnityLoader.js", {
...
}
);
```
--------------------------------
### Get Unity Canvas Reference with React useRef Hook
Source: https://react-unity-webgl.dev/docs/api/canvas-ref
Demonstrates how to use the `useRef` hook in React to get a reference to the Unity Application's Canvas element. This reference can then be used to interact with the canvas, such as focusing it. It's important to note that direct manipulation of the canvas is generally discouraged in favor of Unity Context API functions.
```javascript
import React, { Fragment, useRef } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
const canvasRef = useRef(null);
function focusCanvas() {
if (canvasRef.current) {
canvasRef.current.focus();
}
}
return (
);
}
```
--------------------------------
### Initialize Unity WebGL in React Component
Source: https://react-unity-webgl.dev/docs/7.x.x/getting-started
This snippet demonstrates how to set up a basic React component to embed a Unity WebGL build. It requires the 'react-unity-webgl' library. The code initializes a UnityContent object with paths to the build configuration and loader, then renders the Unity component.
```javascript
import React from "react";
import Unity, { UnityContent } from "react-unity-webgl";
export class App extends React.Component {
constructor(props) {
super(props);
// Next up create a new Unity Content object to
// initialise and define your WebGL build. The
// paths are relative from your index file.
this.unityContent = new UnityContent(
"MyGame/Build.json",
"MyGame/UnityLoader.js"
);
}
render() {
// Finally render the Unity component and pass
// the Unity content through the props.
return ;
}
}
```
--------------------------------
### Get Unity Metrics Info Function Type Definition
Source: https://react-unity-webgl.dev/docs/api/get-metrics-info
Defines the TypeScript signature for the `getMetricsInfo` function, indicating it returns an object of type `UnityMetricsInfo` or `undefined` if metrics are not available.
```typescript
function getMetricsInfo(): UnityMetricsInfo | undefined;
```
--------------------------------
### Get Metrics Info
Source: https://react-unity-webgl.dev/docs/api/get-metrics-info
Retrieves information about the Unity Application's metrics, such as memory usage and frame rate. This function is available in Unity Builds created with Unity 6000.1 or later.
```APIDOC
## GET /metrics
### Description
Retrieves information about the Unity Application's metrics, such as memory usage and frame rate. This can be useful for debugging and performance analysis.
### Method
GET
### Endpoint
`/metrics`
### Parameters
#### Query Parameters
None
#### Path Parameters
None
#### Request Body
None
### Request Example
```
// This function is typically called internally or via a hook
// No direct HTTP request example is applicable here.
```
### Response
#### Success Response (200)
- **fps** (number) - The current frames per second of the Unity Application.
- **memoryUsage** (number) - The current memory usage of the Unity Application in bytes.
- **...?** (other metrics) - Additional performance metrics may be available.
#### Response Example
```json
{
"fps": 60,
"memoryUsage": 123456789
}
```
### Type Definition
```typescript
interface UnityMetricsInfo {
fps: number;
memoryUsage: number;
// ... other properties
}
function getMetricsInfo(): UnityMetricsInfo | undefined;
```
```