@@ -34,6 +34,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
3434 ...canvasProps
3535} : UnityRendererProps ) : JSX . Element | null => {
3636 const [ loader , setLoader ] = useState < UnityLoaderService > ( ) ;
37+ const [ ctx , setCtx ] = useState < UnityContext > ( context ) ;
3738
3839 // We cannot actually render the `HTMLCanvasElement`, so we need the `ref`
3940 // for Unity and a `JSX.Element` for React rendering.
@@ -72,7 +73,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
7273 */
7374 async function mount ( ) : Promise < void > {
7475 // get the current loader configuration from the UnityContext
75- const c = context . getConfig ( ) ;
76+ const c = ctx . getConfig ( ) ;
7677
7778 // attach Unity's native JavaScript loader
7879 await loader ! . execute ( c . loaderUrl ) ;
@@ -92,18 +93,40 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
9293 ) ;
9394
9495 // set the instance for further JavaScript <--> Unity communication
95- context . setInstance ( instance ) ;
96+ ctx . setInstance ( instance ) ;
9697 }
9798
98- // on canvas change
99+ /**
100+ *
101+ */
102+ function unmount ( onComplete ?: ( ) => void ) {
103+ ctx . shutdown ( ( ) => {
104+ // remove the loader script from the DOM
105+ if ( loader ) loader . unmount ( ) ;
106+
107+ // reset progress / ready state
108+ if ( onUnityProgressChange ) onUnityProgressChange ( 0 ) ;
109+ if ( onUnityReadyStateChange ) onUnityReadyStateChange ( false ) ;
110+ setLastReadyState ( false ) ;
111+
112+ if ( onComplete ) onComplete ( ) ;
113+ } ) ;
114+ }
115+
116+ // on loader + renderer ready
117+ useEffect ( ( ) => {
118+ if ( ! loader || ! renderer ) return ;
119+
120+ mount ( ) . catch ( ( e ) => {
121+ if ( onUnityError ) onUnityError ( e ) ;
122+ ctx . shutdown ( ) ;
123+ } ) ;
124+ } , [ loader , renderer , ctx ] ) ;
125+
126+ // on context change
99127 useEffect ( ( ) => {
100- if ( loader && renderer )
101- mount ( ) . catch ( ( e ) => {
102- if ( onUnityError ) onUnityError ( e ) ;
103- if ( onUnityProgressChange ) onUnityProgressChange ( 0 ) ;
104- if ( onUnityReadyStateChange ) onUnityReadyStateChange ( false ) ;
105- } ) ;
106- } , [ loader , renderer ] ) ;
128+ unmount ( ( ) => setCtx ( context ) ) ;
129+ } , [ context ] ) ;
107130
108131 // on mount
109132 useEffect ( ( ) => {
@@ -120,14 +143,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
120143
121144 // on unmount
122145 return ( ) => {
123- context . shutdown ( ( ) => {
124- // remove the loader script from the DOM
125- if ( loader ) loader . unmount ( ) ;
126-
127- // reset progress / ready state
128- if ( onUnityProgressChange ) onUnityProgressChange ( 0 ) ;
129- if ( onUnityReadyStateChange ) onUnityReadyStateChange ( false ) ;
130- } ) ;
146+ unmount ( ) ;
131147 } ;
132148 } , [ ] ) ;
133149
0 commit comments