<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Swatej Gondal on Medium]]></title>
        <description><![CDATA[Stories by Swatej Gondal on Medium]]></description>
        <link>https://medium.com/@swatej23gondal?source=rss-74179c2c261b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Gsqzgb2EFe10Pb7P</url>
            <title>Stories by Swatej Gondal on Medium</title>
            <link>https://medium.com/@swatej23gondal?source=rss-74179c2c261b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:00:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swatej23gondal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating Unity WebGL with React: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@swatej23gondal/integrating-unity-webgl-with-react-a-step-by-step-guide-9c2b9bd18e95?source=rss-74179c2c261b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c2b9bd18e95</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Swatej Gondal]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 11:45:38 GMT</pubDate>
            <atom:updated>2025-06-19T11:45:38.830Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Combining Unity’s rendering capabilities with React’s dynamic UI framework unlocks the potential for engaging, interactive web applications. In this article, I’ll walk you through how I integrated a Unity WebGL application into a React app using the react-unity-webgl npm package, enabling real-time interactions like counter updates and achievement celebrations. Let’s dive in! 🚀</blockquote><h3>Why Unity WebGL + React?</h3><p>Unity WebGL allows developers to deploy interactive content directly in browsers without plugins, ideal for games, simulations, or educational tools. React’s component-based architecture excels at building scalable, interactive UIs. The <a href="https://www.npmjs.com/package/react-unity-webgl">react-unity-webgl</a> package simplifies embedding Unity WebGL builds into React and supports bi-directional communication.</p><p>In this project, I created a demo where clicking a badge in Unity increments a counter, syncs the count with React, and triggers confetti effects in React for milestones (every 25 clicks).</p><h3>Prerequisites</h3><p>Before starting, ensure you have:</p><ul><li><strong>Unity</strong>: Version 2021.3 (or compatible).</li><li><strong>Node.js and npm</strong>: Node 18.x (or compatible).</li><li><strong>A Unity project</strong>: Configured for WebGL export.</li><li><strong>A React project</strong>: Set up with create-react-app or similar.</li><li><strong>Basic knowledge</strong>: Familiarity with Unity, React, and JavaScript.</li></ul><h3>Step 1: Setting Up the Unity Project</h3><p><strong>A. Configure for WebGL</strong>:</p><ul><li>In Unity, go to File &gt; Build Settings, select WebGL, and click Switch Platform.</li><li>In Player Settings, I set Compression Format to Disabled since I’m not using a server for this local setup. (See “Handling Compressed Builds with a Server” below for server-based setups.)</li><li>Enable Decompression Fallback for broader browser compatibility.</li></ul><p><strong>B. Add Communication Logic</strong>:</p><ul><li>Create a GameController.cs script to handle Unity-side logic, such as badge clicks, counter updates, and sending events to React. Below is the relevant code for communication:</li></ul><pre>using System.Runtime.InteropServices;<br>using TMPro;<br>using UnityEngine;<br><br>public class GameController : MonoBehaviour<br>{<br>    [DllImport(&quot;__Internal&quot;)]<br>    private static extern void CallReactMethodFromUnity(int count);<br>    <br>    [DllImport(&quot;__Internal&quot;)]<br>    private static extern void UpdateCountInReact(int count); // For real-time updates<br>    <br>    [SerializeField] private GameObject badge;<br>    [SerializeField] private TextMeshPro countText;<br>    <br>    private int _currentCount;<br>    <br>    void Start()<br>    {<br>        _currentCount = 0;<br>        UpdateCountText();<br>    }<br>    <br>    public void OnClickBadge()<br>    {<br>        _currentCount++;<br>        UpdateCountText();<br>        Debug.Log(&quot;Badge clicked! New count: &quot; + _currentCount);<br>        CheckForAchievement();<br>    }<br><br>    public void OnClickReset()<br>    {<br>        _currentCount = 0;<br>        UpdateCountText();<br>        Debug.Log(&quot;Count reset.&quot;);<br>    }<br><br>    private void UpdateCountText()<br>    {<br>        if (countText)<br>        {<br>            countText.text = _currentCount.ToString();<br>#if UNITY_WEBGL &amp;&amp; !UNITY_EDITOR<br>    UpdateCountInReact(_currentCount); // &lt;- real-time count update<br>#endif<br>        }<br>        else<br>        {<br>            Debug.LogError(&quot;CountText is not assigned in the Inspector!&quot;);<br>        }<br>    }<br><br>    private void CheckForAchievement()<br>    {<br>        if (_currentCount &gt; 0 &amp;&amp; _currentCount % 25 == 0)<br>        {<br>            Debug.Log($&quot;Achievement Unlocked: You have clicked {_currentCount} times.&quot;);<br>            <br>#if UNITY_WEBGL &amp;&amp; !UNITY_EDITOR<br>                CallReactMethodFromUnity(_currentCount);<br>#endif<br>        }<br>    }<br>}</pre><ul><li>OnClickBadge: Increments the counter and notifies React via UpdateCountInReact.</li><li>CheckForAchievement: Sends an achievement event to React for multiples of 25 clicks.</li><li>OnClickReset: Resets the counter and updates React.</li></ul><p><strong>C. Create a JavaScript Bridge</strong>:</p><ul><li>Add a React_WebGL_Bridge.jslib file in Assets/Plugins to enable Unity-to-React communication using custom events:</li></ul><pre>mergeInto(LibraryManager.library, {<br>    CallReactMethodFromUnity : function (count){<br>        window.dispatchEvent(new CustomEvent(&quot;CallReactMethodFromUnity&quot; , {<br>        detail: count}));<br>        console.log(&quot;React Event Fired with count:&quot;, count);<br>    },<br>    <br>    UpdateCountInReact : function UpdateCountInReact(count) {<br>        const event = new CustomEvent(&quot;UpdateCountInReact&quot;, { detail: count });<br>        window.dispatchEvent(event);<br>      }<br>});</pre><ul><li>CallReactMethodFromUnity: Dispatches an achievement event.</li><li>UpdateCountInReact: Dispatches a real-time count update event.</li></ul><p><strong>D. Build the Project</strong>:</p><ul><li>In Build Settings, click Build and output to a folder (e.g., Builds/WebGL). This generates WebGLReactPOC.loader.js, .data, .framework.js, and .wasm files.</li></ul><h3>Step 2: Setting Up the React Project</h3><p><strong>A. Create a React App</strong>:</p><pre>npx create-react-app my-unity-react-app<br>cd my-unity-react-app</pre><p><strong>B. Install </strong><strong>react-unity-webgl</strong>:</p><pre>npm install react-unity-webgl</pre><p><strong>C. Add Unity Build Files</strong>:</p><ul><li>Copy the Unity build files (unity-webgl-react.*) to public/unitybuild in your React project.</li></ul><h3>Step 3: Integrating Unity into React</h3><p>In App.js, use the react-unity-webgl package to embed the Unity canvas and handle communication. Below is the relevant code:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br>import { Unity, useUnityContext } from &quot;react-unity-webgl&quot;;<br>import useConfetti from &quot;./hooks/useConfetti&quot;;<br>import logo from &quot;./logo.svg&quot;;<br>import unityLogo from &quot;./icons8-unity.svg&quot;;<br>import &quot;./App.css&quot;;<br><br>const UNITY_CONFIG = {<br>  GAME_OBJECT: &quot;GameController&quot;,<br>  METHODS: {<br>    ADD_COUNT: &quot;OnClickBadge&quot;,<br>    RESET_COUNT: &quot;OnClickReset&quot;,<br>  },<br>  EVENTS: {<br>    UPDATE_COUNT: &quot;UpdateCountInReact&quot;,   <br>    ACHIEVEMENT: &quot;CallReactMethodFromUnity&quot;, <br>  },<br>};<br><br>function App() {<br>  const [showUnity, setShowUnity] = useState(false);<br>  const [message, setMessage] = useState();<br>  const [toastVisible, setToastVisible] = useState(false);<br>  const { fireRain, fireBurst } = useConfetti();<br>  const [devicePixelRatio, setDevicePixelRatio] = useState(window.devicePixelRatio);<br><br>  const {<br>    unityProvider,<br>    loadingProgression,<br>    isLoaded,<br>    unload,<br>    requestFullscreen,<br>    sendMessage,<br>    addEventListener,<br>    removeEventListener,<br>  } = useUnityContext({<br>    loaderUrl: `${process.env.PUBLIC_URL}/unitybuild/react-unity-webgl.loader.js`,<br>    dataUrl: `${process.env.PUBLIC_URL}/unitybuild/react-unity-webgl.data`,<br>    frameworkUrl: `${process.env.PUBLIC_URL}/unitybuild/react-unity-webgl.framework.js`,<br>    codeUrl: `${process.env.PUBLIC_URL}/unitybuild/react-unity-webgl.wasm`,<br>  });<br><br>  const handleClickFullscreen = async () =&gt; {<br>    if (!isLoaded) return;<br>    try {<br>      await requestFullscreen(true);<br>    } catch (error) {<br>      console.error(&quot;Fullscreen request failed:&quot;, error);<br>    }<br>  };<br><br>  const handleUnloadUnity = async () =&gt; {<br>    if (!isLoaded) return;<br>    try {<br>      await unload();<br>      console.log(&quot;Unload success&quot;);<br>      setShowUnity(false);<br>      setMessage(undefined);<br>      setToastVisible(false);<br>    } catch (error) {<br>      console.error(`Unable to unload: ${error}`);<br>    }<br>  };<br><br>  const handleLoadUnity = () =&gt; {<br>    setShowUnity(true);<br>  };<br><br>  const AddCount = () =&gt; {<br>    if (!isLoaded) return;<br>    try {<br>      sendMessage(UNITY_CONFIG.GAME_OBJECT, UNITY_CONFIG.METHODS.ADD_COUNT);<br>    } catch (error) {<br>      console.error(&quot;Failed to send AddCount message:&quot;, error);<br>    }<br>  };<br><br>  const ResetCounter = () =&gt; {<br>    if (!isLoaded) return;<br>    try {<br>      sendMessage(UNITY_CONFIG.GAME_OBJECT, UNITY_CONFIG.METHODS.RESET_COUNT);<br>    } catch (error) {<br>      console.error(&quot;Failed to send ResetCounter message:&quot;, error);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    const updateDevicePixelRatio = () =&gt; setDevicePixelRatio(window.devicePixelRatio);<br>    const mediaMatcher = window.matchMedia(`screen and (resolution: ${devicePixelRatio}dppx)`);<br>    mediaMatcher.addEventListener(&quot;change&quot;, updateDevicePixelRatio);<br>    return () =&gt; mediaMatcher.removeEventListener(&quot;change&quot;, updateDevicePixelRatio);<br>  }, [devicePixelRatio]);<br><br>  useEffect(() =&gt; {<br>    const handleUpdateCount = (event) =&gt; {<br>      setMessage(parseInt(event.detail, 10));<br>    };<br><br>    const handleAchievement = (event) =&gt; {<br>      const countValue = parseInt(event.detail, 10);<br>      console.log(&quot;Achievement unlocked at count:&quot;, countValue);<br>      setMessage(countValue);<br>      setToastVisible(true);<br>      fireRain();<br>      setTimeout(() =&gt; {<br>        fireBurst();<br>        setToastVisible(false);<br>      }, 1000);<br>    };<br><br>    window.addEventListener(UNITY_CONFIG.EVENTS.UPDATE_COUNT, handleUpdateCount);<br>    window.addEventListener(UNITY_CONFIG.EVENTS.ACHIEVEMENT, handleAchievement);<br><br>    return () =&gt; {<br>      window.removeEventListener(UNITY_CONFIG.EVENTS.UPDATE_COUNT, handleUpdateCount);<br>      window.removeEventListener(UNITY_CONFIG.EVENTS.ACHIEVEMENT, handleAchievement);<br>    };<br>  }, [addEventListener, removeEventListener, fireRain, fireBurst]);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;div className=&quot;logo-container&quot;&gt;<br>          &lt;img src={logo} className=&quot;react-logo&quot; alt=&quot;react-logo&quot; /&gt;<br>          &lt;img src={unityLogo} className=&quot;unity-logo&quot; alt=&quot;unity-logo&quot; /&gt;<br>        &lt;/div&gt;<br>        &lt;p&gt;Unity WebGL in React Website&lt;/p&gt;<br>      &lt;/header&gt;<br><br>      {!showUnity &amp;&amp; (<br>        &lt;button className=&quot;loadUnityBtn&quot; onClick={handleLoadUnity}&gt;<br>          Load Unity Scene<br>        &lt;/button&gt;<br>      )}<br><br>      {showUnity &amp;&amp; toastVisible &amp;&amp; (<br>        &lt;div className=&quot;achievement-toast&quot;&gt;<br>          &lt;p className=&quot;achievement-text&quot;&gt;<br>            Achievement Unlocked! You have clicked {message} times.<br>          &lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br><br>      {showUnity &amp;&amp; &lt;div className=&quot;count&quot;&gt;{message}&lt;/div&gt;}<br><br>      {showUnity &amp;&amp; (<br>        &lt;div className=&quot;UnitySection&quot;&gt;<br>          {!isLoaded &amp;&amp; (<br>            &lt;div className=&quot;UnityLoadingContainer&quot;&gt;<br>              &lt;p className=&quot;UnityLoadingText&quot;&gt;<br>                Loading Unity Application... {Math.round(loadingProgression * 100)}%<br>              &lt;/p&gt;<br>              &lt;div className=&quot;UnityProgressBarContainer&quot;&gt;<br>                &lt;div<br>                  className=&quot;UnityProgressBar&quot;<br>                  style={{ width: `${loadingProgression * 100}%` }}<br>                /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          )}<br>          &lt;Unity<br>            unityProvider={unityProvider}<br>            className={`UnityCanvas ${isLoaded ? &quot;loaded&quot; : &quot;loading&quot;}`}<br>            style={{<br>              width: &quot;1080px&quot;,<br>              maxWidth: &quot;1080px&quot;,<br>              height: &quot;auto&quot;,<br>              maxHeight : &quot;720px&quot;,<br>              visibility: isLoaded ? &quot;visible&quot; : &quot;hidden&quot;,<br>            }}<br>            devicePixelRatio={devicePixelRatio}<br>          /&gt;<br>        &lt;/div&gt;<br>      )}<br><br>      {isLoaded &amp;&amp; showUnity &amp;&amp; (<br>        &lt;div className=&quot;button-container&quot;&gt;<br>          &lt;button className=&quot;button&quot; onClick={handleClickFullscreen}&gt;<br>            Fullscreen<br>          &lt;/button&gt;<br>          &lt;button className=&quot;button&quot; onClick={AddCount}&gt;<br>            Add Count<br>          &lt;/button&gt;<br>          &lt;button className=&quot;button&quot; onClick={ResetCounter}&gt;<br>            Reset Counter<br>          &lt;/button&gt;<br>          &lt;button className=&quot;button&quot; onClick={handleUnloadUnity}&gt;<br>            Unload Scene<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Key Features</strong>:</p><ul><li><strong>Unity Embedding</strong>: The Unity component renders the WebGL canvas, with build file paths specified in useUnityContext.</li><li><strong>Communication</strong>: sendMessage calls Unity methods (OnClickBadge, OnClickReset) via button clicks. Event listeners handle Unity events (UpdateCountInReact, CallReactMethodFromUnity) to update the counter and trigger confetti for achievements.</li><li><strong>UI Feedback</strong>: Displays the current count and shows a toast with confetti animations for milestones (every 25 clicks).</li></ul><h3>Step 4: Handling Compressed Builds with a Server</h3><p>If deploying to a server with a compressed Unity WebGL build (Brotli or Gzip), follow these steps to ensure proper delivery:</p><ol><li><strong>Set Compression in Unity</strong>:</li></ol><ul><li>In Player Settings, set Compression Format to Brotli (preferred for smaller sizes) or Gzip.</li><li>Rebuild the project to generate compressed files (e.g., .data.br or .data.gz).</li></ul><p><strong>Configure the Server</strong>:</p><ul><li>Ensure the server supports serving compressed files with correct MIME types and headers:</li><li>For Brotli: Serve .br files with Content-Encoding: br.</li><li>For Gzip: Serve .gz files with Content-Encoding: gzip.</li><li>Common MIME types:</li><li>.loader.js: application/javascript</li><li>.data, .data.br, .data.gz: application/octet-stream</li><li>.framework.js, .framework.js.br, .framework.js.gz: application/javascript</li><li>.wasm, .wasm.br, .wasm.gz: application/wasm</li></ul><p><strong>Update React Paths</strong>:</p><ul><li>In App.js, ensure useUnityContext points to the uncompressed or compressed file extensions based on server support. For example, if using Brotli, the server will automatically serve .data.br when requesting .data if configured correctly.</li></ul><p><strong>Test Compression</strong>:</p><ul><li>Deploy to the server and verify in the browser’s DevTools (Network tab) that files are served with the correct Content-Encoding header and load without errors.</li></ul><p>Since I used Compression Format: Disabled for local testing, these steps were not needed, but they’re critical for production servers to reduce load times.</p><h3>Step 5: Optimizing for Performance</h3><ul><li><strong>Unity</strong>: Optimize assets (e.g., sprites, audio) .</li><li><strong>React</strong>: Use useEffect to clean up event listeners and manage the Unity instance lifecycle.</li><li><strong>Testing</strong>: Test on Chrome, Firefox, and Safari for WebGL compatibility.</li></ul><h3>Step 6: Deployment</h3><p><strong>Local Testing</strong>:</p><ul><li>Run npm start to test locally. Verify the Unity canvas loads, button clicks update the counter, and achievements trigger confetti.</li></ul><p><strong>Deploy</strong>:</p><ul><li>Build with npm run build and deploy to Netlify, GitHub Pages, or a custom server.</li><li>For uncompressed builds (as in my case), no special server configuration is needed. For compressed builds, follow the server setup above.</li><li>Ensure WebGL files are served with correct MIME types (e.g., .wasm as application/wasm).</li></ul><h3>Try It Out!</h3><p>I’ve shared the project on GitHub, including a demo, setup instructions, and the full integration. Check it out: <a href="https://github.com/Swatej23/unity-webgl-react">https://github.com/Swatej23/unity-webgl-react</a></p><p>Have you worked on Unity WebGL or React integrations? Share your projects or ideas in the comments — I’d love to connect! 🚀</p><p><em>See the code in action on </em><a href="https://swatej23.github.io/unity-webgl-react/">https://swatej23.github.io/unity-webgl-react/</a></p><p>#Unity #React #WebGL #WebDevelopment #GameDev #FrontendDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c2b9bd18e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>