Skip to content

Commit 0b9e4e2

Browse files
fix: add random ID to canvas to mitigate Unity 2021.x behavior
1 parent 36b7406 commit 0b9e4e2

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/components/UnityRenderer.tsx

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { UnityContext } from '../lib/context';
55

66
export type UnityRendererProps = Omit<
77
HTMLAttributes<HTMLCanvasElement>,
8-
'ref'
8+
'ref' | 'id'
99
> & {
1010
context?: UnityContext;
1111
onUnityProgressChange?: (progress: number) => void;
@@ -30,6 +30,15 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
3030
onUnityError,
3131
...canvasProps
3232
}: UnityRendererProps): JSX.Element | null => {
33+
// an ID must be applied to the canvas element, else the Unity 2021.x
34+
// WebGL framework will fail for no good reason but messing with devs.
35+
// Here you go Unity, have a random one.
36+
const instanceId = useRef<string>(
37+
`unity-renderer-${[...Array(8)]
38+
.map(() => Math.floor(Math.random() * 16).toString(16))
39+
.join('')}`
40+
);
41+
3342
const [ctx, setCtx] = useState<UnityContext | undefined>(context);
3443
const [loaderState, setLoaderSource] = useScript(ctx?.getConfig().loaderUrl);
3544

@@ -174,5 +183,5 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
174183
useEffect(() => () => unmount(), []);
175184

176185
// eslint-disable-next-line react/jsx-props-no-spreading
177-
return <canvas {...canvasProps} ref={canvas} />;
186+
return <canvas {...canvasProps} ref={canvas} id={instanceId.current} />;
178187
};

0 commit comments

Comments
 (0)