@@ -34,6 +34,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
34
34
...canvasProps
35
35
} : UnityRendererProps ) : JSX . Element | null => {
36
36
const [ loader , setLoader ] = useState < UnityLoaderService > ( ) ;
37
+ const [ ctx , setCtx ] = useState < UnityContext > ( context ) ;
37
38
38
39
// We cannot actually render the `HTMLCanvasElement`, so we need the `ref`
39
40
// for Unity and a `JSX.Element` for React rendering.
@@ -72,7 +73,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
72
73
*/
73
74
async function mount ( ) : Promise < void > {
74
75
// get the current loader configuration from the UnityContext
75
- const c = context . getConfig ( ) ;
76
+ const c = ctx . getConfig ( ) ;
76
77
77
78
// attach Unity's native JavaScript loader
78
79
await loader ! . execute ( c . loaderUrl ) ;
@@ -92,18 +93,40 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
92
93
) ;
93
94
94
95
// set the instance for further JavaScript <--> Unity communication
95
- context . setInstance ( instance ) ;
96
+ ctx . setInstance ( instance ) ;
96
97
}
97
98
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
99
127
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 ] ) ;
107
130
108
131
// on mount
109
132
useEffect ( ( ) => {
@@ -120,14 +143,7 @@ export const UnityRenderer: VFC<UnityRendererProps> = ({
120
143
121
144
// on unmount
122
145
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 ( ) ;
131
147
} ;
132
148
} , [ ] ) ;
133
149
0 commit comments