Skip to content

Commit

Permalink
UnityContent: detect instance events
Browse files Browse the repository at this point in the history
Events which are dispatched via triggerUnityEvents() are instance
specific events that do not need a global event handler attached to
ReactUnityWebGL object. All other event names are assumed to be global
ones.

Fixes jeffreylanters#109
  • Loading branch information
stefanb2 committed Aug 14, 2020
1 parent a293feb commit 48f6130
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions source/UnityContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ import "./declarations/UnityInstance";
import "./declarations/ReactUnityWebGL";
import { loggingService } from "./services/LoggingService";

// event names on which this.triggerUnityEvent() is called
const InstanceEventNames: string[] = [
'error',
'loaded',
'progress',
'quitted',
'resized',
];

export default class UnityContent {
/**
* the relative path to the build json file generated by Unity.
Expand Down Expand Up @@ -176,12 +185,19 @@ export default class UnityContent {
* @public
*/
public on(eventName: string, eventCallback: Function): any {
this.unityInstanceEvents.AddEventListener(eventName, eventCallback);

UnityContent.unityGlobalEvents.AddEventListener(eventName, eventCallback);
if (typeof (window as any).ReactUnityWebGL[eventName] === 'undefined') {
(window as any).ReactUnityWebGL[eventName] = (parameter: any) =>
UnityContent.unityGlobalEvents.DispatchEvent(eventName, parameter);
if (InstanceEventNames.find(name => name === eventName)) {
// instance event - add to instance events
this.unityInstanceEvents.AddEventListener(eventName, eventCallback);

} else {
// ReactUnityWebGL event - add to class events
UnityContent.unityGlobalEvents.AddEventListener(eventName, eventCallback);

// install global event handler (if necessary)
if (typeof (window as any).ReactUnityWebGL[eventName] === 'undefined') {
(window as any).ReactUnityWebGL[eventName] = (parameter: any) =>
UnityContent.unityGlobalEvents.DispatchEvent(eventName, parameter);
}
}
}

Expand Down

0 comments on commit 48f6130

Please sign in to comment.