Use the UnityInstance after createUnityInstance #435
-
Hi there, At the moment I'm working on an implementation where I need to use the UnityInstance for other JS scripts. Below you see how the callback of the
I wonder how to achieve this with the latest version of Many thanks already for sharing insights :). Best, Ruben |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 17 replies
-
Hi Ruben, There is currently no way to get a reference to the Unity Instance. You could however create a React Unity event in order to pass data back and forth, since these events cannot only be invoked from Unity, but in reality can be invoked from any script living on the page. Is this something that might help you? Keep me posted! |
Beta Was this translation helpful? Give feedback.
-
Thanks for the details and thinking with me @rubenlangeweg. I've looked into the code of several third party plugins including Agora, and came to the conclusion that exposing the Unity Instance within React via the Unity Context hook seems to be the most reliable and scalable way to go. Especially when looking into the future where more third party implementations might required its access. In the latest release version 9.2.0, I've implemented this API (with a caution) where the Unity Instance is being exposed to do with it as you like. You can visit the docs to read more about it: In the following example we'll bind the Unity Instance to the window so external scripts can access it. 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 <Unity unityProvider={unityProvider} />;
} I hope this both (@uncle-mo) helps you with your development. If you're having any further questions, feel free reply on this thread. Happy coding! |
Beta Was this translation helpful? Give feedback.
Thanks for the details and thinking with me @rubenlangeweg. I've looked into the code of several third party plugins including Agora, and came to the conclusion that exposing the Unity Instance within React via the Unity Context hook seems to be the most reliable and scalable way to go. Especially when looking into the future where more third party implementations might required its access.
In the latest release version 9.2.0, I've implemented this API (with a caution) where the Unity Instance is being exposed to do with it as you like. You can visit the docs to read more about it:
https://react-unity-webgl.dev/docs/api/unsafe-unity-instance
In the following example we'll bind the Unity I…