Skip to content

Sample with devicePixelRatio update rerenders the app #532

Open
@Hemaolle

Description

@Hemaolle

Please avoid duplicates

Language and Compiler

Babel and WebPack TypeScript

What environment are you using?

Local Development Server

When does your problem occur?

When the Unity App is running

What does your problem relate to?

The problem seems Module related

React-Unity-WebGL Version

9.3.0

React Version

^18.x.x

Unity Version

2022.3.9f1

What happened?

Following the documentation for dynamic device pixel ratio (https://react-unity-webgl.dev/docs/advanced-examples/dynamic-device-pixel-ratio) leads to the app rerendering when the tab is dragged to a display with a different device pixel ratio (changed from Windows display setting Scale)

image (11)-1

Reproducible test case

// from https://react-unity-webgl.dev/docs/advanced-examples/dynamic-device-pixel-ratio

import React, { useState, useEffect } 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 use a state to store the device pixel ratio.
  const [devicePixelRatio, setDevicePixelRatio] = useState(
    window.devicePixelRatio
  );

  useEffect(
    function () {
      // A function which will update the device pixel ratio of the Unity
      // Application to match the device pixel ratio of the browser.
      const updateDevicePixelRatio = function () {
        setDevicePixelRatio(window.devicePixelRatio);
      };
      // A media matcher which watches for changes in the device pixel ratio.
      const mediaMatcher = window.matchMedia(
        `screen and (resolution: ${devicePixelRatio}dppx)`
      );
      // Adding an event listener to the media matcher which will update the
      // device pixel ratio of the Unity Application when the device pixel
      // ratio changes.
      mediaMatcher.addEventListener("change", updateDevicePixelRatio);
      return function () {
        // Removing the event listener when the component unmounts.
        mediaMatcher.removeEventListener("change", updateDevicePixelRatio);
      };
    },
    [devicePixelRatio]
  );

  return (
    <Unity
      unityProvider={unityProvider}
      style={{ width: 800, height: 600 }}
      devicePixelRatio={devicePixelRatio}
    />
  );
}

Would you be interested in contributing a fix?

  • yes, I would like to contribute a fix

Metadata

Metadata

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions