@pizzapopcorn/unijs 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/unity.js CHANGED
@@ -15,6 +15,12 @@
15
15
  destroy: {}
16
16
  }
17
17
 
18
+ /**
19
+ * Gets a GameObject by its JS Key (previously set in Unity using the JSKeyGameObject component).
20
+ * @param {string} key
21
+ * @returns {GameObject | null}
22
+ * @constructor
23
+ */
18
24
  static GetKeyGameObject(key){
19
25
  if(!GameObject.keyGameObjects.hasOwnProperty(key)) {
20
26
  console.error(`GameObject with key '${key}' not found`);
@@ -23,6 +29,11 @@
23
29
  return GameObject.keyGameObjects[key];
24
30
  }
25
31
 
32
+ /**
33
+ * Registers a callback for a GameObject's Awake event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created.
34
+ * @param {string} key
35
+ * @param {function} callback
36
+ */
26
37
  static onAwake(key, callback){
27
38
  if(!GameObject.#lifeCycleCallbacks.awake.hasOwnProperty(key)) {
28
39
  GameObject.#lifeCycleCallbacks.awake[key] = new Set();
@@ -30,6 +41,11 @@
30
41
  GameObject.#lifeCycleCallbacks.awake[key].add(callback);
31
42
  }
32
43
 
44
+ /**
45
+ * Registers a callback for a GameObject's Start event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created.
46
+ * @param {string} key
47
+ * @param {function} callback
48
+ */
33
49
  static onStart(key, callback) {
34
50
  if(!GameObject.#lifeCycleCallbacks.start.hasOwnProperty(key)) {
35
51
  GameObject.#lifeCycleCallbacks.start[key] = new Set();
@@ -37,6 +53,11 @@
37
53
  GameObject.#lifeCycleCallbacks.start[key].add(callback);
38
54
  }
39
55
 
56
+ /**
57
+ * Registers a callback for a GameObject's OnEnable event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created.
58
+ * @param {string} key
59
+ * @param {function} callback
60
+ */
40
61
  static onEnable(key, callback) {
41
62
  if(!GameObject.#lifeCycleCallbacks.enable.hasOwnProperty(key)) {
42
63
  GameObject.#lifeCycleCallbacks.enable[key] = new Set();
@@ -44,6 +65,11 @@
44
65
  GameObject.#lifeCycleCallbacks.enable[key].add(callback);
45
66
  }
46
67
 
68
+ /**
69
+ * Registers a callback for a GameObject's OnDisable event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created and then disabled.
70
+ * @param {string} key
71
+ * @param {function} callback
72
+ */
47
73
  static onDisable(key, callback) {
48
74
  if(!GameObject.#lifeCycleCallbacks.disable.hasOwnProperty(key)) {
49
75
  GameObject.#lifeCycleCallbacks.disable[key] = new Set();
@@ -51,6 +77,11 @@
51
77
  GameObject.#lifeCycleCallbacks.disable[key].add(callback);
52
78
  }
53
79
 
80
+ /**
81
+ * Registers a callback for a GameObject's Destroy event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created and then destroyed.
82
+ * @param {string} key
83
+ * @param {function} callback
84
+ */
54
85
  static onDestroy(key, callback) {
55
86
  if(!GameObject.#lifeCycleCallbacks.destroy.hasOwnProperty(key)) {
56
87
  GameObject.#lifeCycleCallbacks.destroy[key] = new Set();
@@ -85,15 +116,31 @@
85
116
  this.hierarchyPath = data.hasOwnProperty("hierarchyPath") ? data.hierarchyPath : "";
86
117
  }
87
118
 
119
+ /**
120
+ * Sets the GameObject's active state.
121
+ * @param {boolean} active
122
+ */
88
123
  SetActive(active) {
89
124
  this?.#invokeGameObjectEvent("gameObject.setActive", active);
90
125
  }
91
126
 
127
+ /**
128
+ * Invokes a method on the GameObject via SendMessage. Use GameObject.types for type options.
129
+ * <br>In order for it to work with custom types, you need to get the fully qualified name of the type.
130
+ * @param {string} methodName
131
+ * @param {string} paramType
132
+ * @param {string} paramValue
133
+ */
92
134
  InvokeMethod(methodName, paramType = "", paramValue = "") {
93
135
  paramType = Unity.types[paramType] || paramType;
94
136
  this?.#invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
95
137
  }
96
138
 
139
+ /**
140
+ * Gets a child GameObject by index or name.
141
+ * @param {number | string} query
142
+ * @returns {GameObject | null}
143
+ */
97
144
  GetChild(query) {
98
145
  const eventName = typeof query === "string" ? "gameObject.findChild" : "gameObject.getChild";
99
146
  const childData = this?.#invokeGameObjectEvent(eventName, query);
@@ -105,26 +152,57 @@
105
152
  return null;
106
153
  }
107
154
 
155
+ /**
156
+ * Translates the GameObject's position by the specified amount on each axis.
157
+ * @param {number} x
158
+ * @param {number} y
159
+ * @param {number} z
160
+ */
108
161
  Translate(x, y, z) {
109
162
  this?.#invokeGameObjectEvent("transform.translate", { x: x, y: y, z: z });
110
163
  }
111
164
 
165
+ /**
166
+ * Rotates the GameObject around its local axis by the specified amount in degrees.
167
+ * @param {number} x
168
+ * @param {number} y
169
+ * @param {number} z
170
+ */
112
171
  Rotate(x, y, z) {
113
172
  this?.#invokeGameObjectEvent("transform.rotate", { x: x, y: y, z: z });
114
173
  }
115
174
 
175
+ /**
176
+ * Sets the GameObject's local scale to the specified values.
177
+ * @param {number} x
178
+ * @param {number} y
179
+ * @param {number} z
180
+ */
116
181
  SetLocalScale(x, y, z) {
117
182
  this?.#invokeGameObjectEvent("transform.setLocalScale", { x: x, y: y, z: z });
118
183
  }
119
184
 
185
+ /**
186
+ * Sets the GameObject's local position to the specified values.
187
+ * @param {number} x
188
+ * @param {number} y
189
+ * @param {number} z
190
+ */
120
191
  SetLocalPosition(x, y, z) {
121
192
  this?.#invokeGameObjectEvent("transform.setLocalPosition", { x: x, y: y, z: z });
122
193
  }
123
194
 
195
+ /**
196
+ * Looks for a text component and sets its text to the specified value. It works with Legacy, TextMeshPro, and TextMesh components.
197
+ * @param {string} text
198
+ */
124
199
  SetText(text) {
125
200
  this?.#invokeGameObjectEvent("text.setText", text);
126
201
  }
127
202
 
203
+ /**
204
+ * Destroys the GameObject.
205
+ */
128
206
  Destroy() {
129
207
  this?.#invokeGameObjectEvent("gameObject.destroy", "");
130
208
  }
@@ -185,6 +263,11 @@
185
263
  static #onInstanceReadyListeners = new Set();
186
264
  static #onEventListeners = {};
187
265
 
266
+ /**
267
+ * Loads the Unity canvas from the specified URL and injects it into the specified element.
268
+ * @param {string} url
269
+ * @param {string} elementId
270
+ */
188
271
  static LoadInstance(url, elementId) {
189
272
  Unity.#instanceReady = false;
190
273
  const r = new XMLHttpRequest();
@@ -207,10 +290,29 @@
207
290
  r.send();
208
291
  }
209
292
 
293
+ /**
294
+ * Gets the current Unity version.
295
+ * @returns {string}
296
+ */
297
+ static GetVersion() {
298
+ return Unity.InvokeEvent("InstanceEvent:GetUnityVersion");
299
+ }
300
+
301
+ /**
302
+ * Gets the current build version.
303
+ * @returns {string}
304
+ */
210
305
  static GetBuildVersion() {
211
306
  return Unity.InvokeEvent("InstanceEvent:GetBuildVersion");
212
307
  }
213
308
 
309
+ /**
310
+ * Invokes a global event that can be listened to by both Unity and JS.
311
+ * An optional payload can be sent, and the event can also return anything.
312
+ * @param {string} eventName
313
+ * @param {any} payload
314
+ * @returns {any}
315
+ */
214
316
  static InvokeEvent(eventName, payload = undefined) {
215
317
  const responseJson = Unity.#invokeEventInternal(eventName, payload);
216
318
  try {
@@ -228,6 +330,13 @@
228
330
  }
229
331
  }
230
332
 
333
+ /**
334
+ * Async version of InvokeEvent. Invokes a global async event that can be listened to by both Unity and JS.
335
+ * An optional payload can be sent, and the event can also return anything.
336
+ * @param {string} eventName
337
+ * @param {any} payload
338
+ * @returns {Promise<any>}
339
+ */
231
340
  static async InvokeEventAsync(eventName, payload = undefined) {
232
341
  return new Promise(resolve => {
233
342
  const responseJson = Unity.#invokeEventInternal(eventName, payload);
@@ -248,6 +357,10 @@
248
357
  })
249
358
  }
250
359
 
360
+ /**
361
+ * Awaits the Unity WaitForEndOfFrame coroutine.
362
+ * @returns {Promise<void>}
363
+ */
251
364
  static async WaitForEndOfFrameAsync() {
252
365
  return new Promise((resolve) => {
253
366
  const eventId = crypto.randomUUID().toString();
@@ -262,10 +375,56 @@
262
375
  });
263
376
  }
264
377
 
378
+ /**
379
+ * Loads a scene and awaits its completion.
380
+ * @param {string} sceneName
381
+ * @returns {Promise<void>}
382
+ */
383
+ static async LoadSceneAsync(sceneName) {
384
+ return new Promise((resolve) => {
385
+ const eventName = `SceneLoadedEvent:${sceneName}`;
386
+ Unity.onEvent(eventName, () => {
387
+ resolve();
388
+ delete Unity.#onEventListeners[eventName];
389
+ });
390
+
391
+ Unity.InvokeEvent("InstanceEvent:LoadScene", sceneName);
392
+ });
393
+ }
394
+
395
+ /**
396
+ * Returns true if a scene is currently loading.
397
+ * @returns {boolean}
398
+ */
399
+ static IsSceneLoading() {
400
+ return Unity.InvokeEvent("InstanceEvent:IsSceneLoading");
401
+ }
402
+
403
+ /**
404
+ * Returns the current scene load progress. If no scene is currently loading, it returns 0.
405
+ * @returns {number}
406
+ */
407
+ static GetSceneLoadProgress() {
408
+ return Unity.InvokeEvent("InstanceEvent:GetSceneLoadProgress");
409
+ }
410
+
411
+ /**
412
+ * Loads an asset bundle from the provided URL and awaits its completion.
413
+ * @param {string} bundleUrl
414
+ * @returns {Promise<void>}
415
+ */
265
416
  static async LoadBundleAsync(bundleUrl) {
266
417
  await Unity.InvokeEventAsync("InstanceEvent:LoadBundle", bundleUrl);
267
418
  }
268
419
 
420
+ /**
421
+ * This function loads the bundle, instantiates a prefab from it, and then unloads the bundle so you don't have to handle it manually.
422
+ * An optional parent JS Key can be provided to place the instantiated prefab under a specific GameObject.
423
+ * @param {string} bundleUrl
424
+ * @param {string} prefabName
425
+ * @param {string} parentKey
426
+ * @returns {Promise<void>}
427
+ */
269
428
  static async InstantiatePrefabFromBundleAsync(bundleUrl, prefabName, parentKey = "") {
270
429
  await Unity.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle", {
271
430
  bundleUrl: bundleUrl,
@@ -276,6 +435,10 @@
276
435
 
277
436
  // Listeners -----------------------------
278
437
 
438
+ /**
439
+ * Registers a callback that will be invoked when the Unity instance is ready.
440
+ * @param {function} callback
441
+ */
279
442
  static onInstanceReady(callback) {
280
443
  if(!Unity.#instanceReady) {
281
444
  Unity.#onInstanceReadyListeners.add(callback);
@@ -285,6 +448,11 @@
285
448
  }
286
449
  }
287
450
 
451
+ /**
452
+ * Registers a callback that will be invoked when a global event is received. It can listen to events from both Unity and JS.
453
+ * @param {string} eventName
454
+ * @param {function} callback
455
+ */
288
456
  static onEvent(eventName, callback) {
289
457
  if(!Unity.#onEventListeners.hasOwnProperty(eventName)) {
290
458
  Unity.#onEventListeners[eventName] = new Set();
@@ -292,6 +460,11 @@
292
460
  Unity.#onEventListeners[eventName].add(callback);
293
461
  }
294
462
 
463
+ /**
464
+ * Unregisters a callback previously registered with onEvent.
465
+ * @param {string} eventName
466
+ * @param {function} callback
467
+ */
295
468
  static offEvent(eventName, callback) {
296
469
  if(!Unity.#onEventListeners.hasOwnProperty(eventName)) return;
297
470
  Unity.#onEventListeners[eventName].delete(callback);
package/dist/unity.min.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Unity=t()}(this,function(){"use strict";class e{static keyGameObjects={};static#e={awake:{},start:{},enable:{},disable:{},destroy:{}};static GetKeyGameObject(t){return e.keyGameObjects.hasOwnProperty(t)?e.keyGameObjects[t]:(console.error(`GameObject with key '${t}' not found`),null)}static onAwake(t,n){e.#e.awake.hasOwnProperty(t)||(e.#e.awake[t]=new Set),e.#e.awake[t].add(n)}static onStart(t,n){e.#e.start.hasOwnProperty(t)||(e.#e.start[t]=new Set),e.#e.start[t].add(n)}static onEnable(t,n){e.#e.enable.hasOwnProperty(t)||(e.#e.enable[t]=new Set),e.#e.enable[t].add(n)}static onDisable(t,n){e.#e.disable.hasOwnProperty(t)||(e.#e.disable[t]=new Set),e.#e.disable[t].add(n)}static onDestroy(t,n){e.#e.destroy.hasOwnProperty(t)||(e.#e.destroy[t]=new Set),e.#e.destroy[t].add(n)}static _register(t,n){e.keyGameObjects[t]=new e(t,n)}static _receiveLifeCycleEvent(t,n){const s=e.keyGameObjects[t];if(!s)return;const a=e.#e[n][t];if(a)for(const e of a)e(s);"destroy"===n&&(s.transform=null,delete e.keyGameObjects[t])}constructor(e,t){this.key=e,this.name=t.name,this.transform=t.transform,this.hierarchyPath=t.hasOwnProperty("hierarchyPath")?t.hierarchyPath:""}SetActive(e){this?.#t("gameObject.setActive",e)}InvokeMethod(e,t="",n=""){t=Unity.types[t]||t,this?.#t("gameObject.invokeMethod",{methodName:e,parameterType:t,parameterValue:n})}GetChild(t){const n="string"==typeof t?"gameObject.findChild":"gameObject.getChild",s=this?.#t(n,t);if(null!==s){const t=""===this.hierarchyPath?this.key:this.hierarchyPath;return s.hierarchyPath=t+"/"+s.name,new e(this.key,s)}return null}Translate(e,t,n){this?.#t("transform.translate",{x:e,y:t,z:n})}Rotate(e,t,n){this?.#t("transform.rotate",{x:e,y:t,z:n})}SetLocalScale(e,t,n){this?.#t("transform.setLocalScale",{x:e,y:t,z:n})}SetLocalPosition(e,t,n){this?.#t("transform.setLocalPosition",{x:e,y:t,z:n})}SetText(e){this?.#t("text.setText",e)}Destroy(){this?.#t("gameObject.destroy","")}#t(e,t){if(!this.transform)return null;let n=t;"object"==typeof t?n=JSON.stringify(t):"string"!=typeof t&&(n=t.toString());const s={eventName:e,hierarchyPath:this.hierarchyPath,payloadJson:n,listenDisabled:!0},a=Unity.InvokeEvent(`GOEvent:${this.key}`,JSON.stringify(s));if(Unity.internalLogs&&console.log(`Invoked Event: GOEvent:${this.key}`,s),null===a||!a.hasOwnProperty("ok"))return console.error(`Invalid JSON response from GameObject event callback: ${a}`),null;if(a.ok){let e=a.responseJson;try{e=JSON.parse(a.responseJson)}catch{}return e}return console.error(`Error invoking GameObject event: ${e}`,a.error),null}}return class t{static GameObject=e;static internalLogs=!1;static types={int:"System.Int32",float:"System.Single",double:"System.Double",bool:"System.Boolean",string:"System.String",char:"System.Char",byte:"System.Byte",long:"System.Int64",short:"System.Int16",decimal:"System.Decimal",object:"System.Object",customClass:(e,t="",n="Assembly-CSharp")=>`${""===t?e:`${t}.${e}`}, ${n}.dll`};static#n;static#s=!1;static#a=new Set;static#r={};static LoadInstance(e,n){t.#s=!1;const s=new XMLHttpRequest;s.open("GET",e+"/index.html",!0),s.onreadystatechange=function(){if(4!==s.readyState||200!==s.status)return;document.querySelector(`#${n}`).innerHTML=s.responseText;const t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e+"/TemplateData/style.css",document.head.appendChild(t);const a=document.createElement("script");a.src=e+"/index.js",document.body.appendChild(a)},s.send()}static GetBuildVersion(){return t.InvokeEvent("InstanceEvent:GetBuildVersion")}static InvokeEvent(e,n=void 0){const s=t.#o(e,n);try{const n=JSON.parse(s);return n.hasOwnProperty("promiseId")&&(console.warn(`Event '${e}' returned a promise. Consider using InvokeEventAsync instead.`),t.onEvent(`PromiseResolvedEvent:${n.promiseId}`,e=>{delete t.#r[`PromiseResolvedEvent:${n.promiseId}`]})),n}catch{return s}}static async InvokeEventAsync(e,n=void 0){return new Promise(s=>{const a=t.#o(e,n);try{const e=JSON.parse(a);e.hasOwnProperty("promiseId")?t.onEvent(`PromiseResolvedEvent:${e.promiseId}`,n=>{s(n),delete t.#r[`PromiseResolvedEvent:${e.promiseId}`]}):s(e)}catch{s(a)}})}static async WaitForEndOfFrameAsync(){return new Promise(e=>{const n=crypto.randomUUID().toString(),s=`EndOfFrameEvent:${n}`;t.onEvent(s,()=>{e(),delete t.#r[s]}),t.InvokeEvent("InstanceEvent:WaitForEndOfFrame",n)})}static async LoadBundleAsync(e){await t.InvokeEventAsync("InstanceEvent:LoadBundle",e)}static async InstantiatePrefabFromBundleAsync(e,n,s=""){await t.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle",{bundleUrl:e,prefabName:n,parentKey:s})}static onInstanceReady(e){t.#s?e():t.#a.add(e)}static onEvent(e,n){t.#r.hasOwnProperty(e)||(t.#r[e]=new Set),t.#r[e].add(n)}static offEvent(e,n){t.#r.hasOwnProperty(e)&&t.#r[e].delete(n)}static#o(e,n){null==n&&(n="");let s=n;"object"==typeof n?s=JSON.stringify(n):"string"!=typeof n&&(s=n.toString());const a=t.#n(e,s);return t.#r[e]?.forEach(e=>e(s)),a}static _instanceReady(){t.#s=!0,t.#a.forEach(e=>e())}static _registerClientListener(e){t.#n=e}static _receiveEvent(e,n){let s=n;try{s=JSON.parse(n)}catch{}t.InvokeEvent(e,s)}static _logFromUnity(e,n){("internal"!==e||t.internalLogs)&&("error"===e?console.error(`[Unity] ${n}`):"warning"===e?console.warn(`[Unity] ${n}`):console.log(`[Unity] ${n}`))}}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Unity=t()}(this,function(){"use strict";class e{static keyGameObjects={};static#e={awake:{},start:{},enable:{},disable:{},destroy:{}};static GetKeyGameObject(t){return e.keyGameObjects.hasOwnProperty(t)?e.keyGameObjects[t]:(console.error(`GameObject with key '${t}' not found`),null)}static onAwake(t,n){e.#e.awake.hasOwnProperty(t)||(e.#e.awake[t]=new Set),e.#e.awake[t].add(n)}static onStart(t,n){e.#e.start.hasOwnProperty(t)||(e.#e.start[t]=new Set),e.#e.start[t].add(n)}static onEnable(t,n){e.#e.enable.hasOwnProperty(t)||(e.#e.enable[t]=new Set),e.#e.enable[t].add(n)}static onDisable(t,n){e.#e.disable.hasOwnProperty(t)||(e.#e.disable[t]=new Set),e.#e.disable[t].add(n)}static onDestroy(t,n){e.#e.destroy.hasOwnProperty(t)||(e.#e.destroy[t]=new Set),e.#e.destroy[t].add(n)}static _register(t,n){e.keyGameObjects[t]=new e(t,n)}static _receiveLifeCycleEvent(t,n){const s=e.keyGameObjects[t];if(!s)return;const a=e.#e[n][t];if(a)for(const e of a)e(s);"destroy"===n&&(s.transform=null,delete e.keyGameObjects[t])}constructor(e,t){this.key=e,this.name=t.name,this.transform=t.transform,this.hierarchyPath=t.hasOwnProperty("hierarchyPath")?t.hierarchyPath:""}SetActive(e){this?.#t("gameObject.setActive",e)}InvokeMethod(e,t="",n=""){t=Unity.types[t]||t,this?.#t("gameObject.invokeMethod",{methodName:e,parameterType:t,parameterValue:n})}GetChild(t){const n="string"==typeof t?"gameObject.findChild":"gameObject.getChild",s=this?.#t(n,t);if(null!==s){const t=""===this.hierarchyPath?this.key:this.hierarchyPath;return s.hierarchyPath=t+"/"+s.name,new e(this.key,s)}return null}Translate(e,t,n){this?.#t("transform.translate",{x:e,y:t,z:n})}Rotate(e,t,n){this?.#t("transform.rotate",{x:e,y:t,z:n})}SetLocalScale(e,t,n){this?.#t("transform.setLocalScale",{x:e,y:t,z:n})}SetLocalPosition(e,t,n){this?.#t("transform.setLocalPosition",{x:e,y:t,z:n})}SetText(e){this?.#t("text.setText",e)}Destroy(){this?.#t("gameObject.destroy","")}#t(e,t){if(!this.transform)return null;let n=t;"object"==typeof t?n=JSON.stringify(t):"string"!=typeof t&&(n=t.toString());const s={eventName:e,hierarchyPath:this.hierarchyPath,payloadJson:n,listenDisabled:!0},a=Unity.InvokeEvent(`GOEvent:${this.key}`,JSON.stringify(s));if(Unity.internalLogs&&console.log(`Invoked Event: GOEvent:${this.key}`,s),null===a||!a.hasOwnProperty("ok"))return console.error(`Invalid JSON response from GameObject event callback: ${a}`),null;if(a.ok){let e=a.responseJson;try{e=JSON.parse(a.responseJson)}catch{}return e}return console.error(`Error invoking GameObject event: ${e}`,a.error),null}}return class t{static GameObject=e;static internalLogs=!1;static types={int:"System.Int32",float:"System.Single",double:"System.Double",bool:"System.Boolean",string:"System.String",char:"System.Char",byte:"System.Byte",long:"System.Int64",short:"System.Int16",decimal:"System.Decimal",object:"System.Object",customClass:(e,t="",n="Assembly-CSharp")=>`${""===t?e:`${t}.${e}`}, ${n}.dll`};static#n;static#s=!1;static#a=new Set;static#r={};static LoadInstance(e,n){t.#s=!1;const s=new XMLHttpRequest;s.open("GET",e+"/index.html",!0),s.onreadystatechange=function(){if(4!==s.readyState||200!==s.status)return;document.querySelector(`#${n}`).innerHTML=s.responseText;const t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e+"/TemplateData/style.css",document.head.appendChild(t);const a=document.createElement("script");a.src=e+"/index.js",document.body.appendChild(a)},s.send()}static GetVersion(){return t.InvokeEvent("InstanceEvent:GetUnityVersion")}static GetBuildVersion(){return t.InvokeEvent("InstanceEvent:GetBuildVersion")}static InvokeEvent(e,n=void 0){const s=t.#o(e,n);try{const n=JSON.parse(s);return n.hasOwnProperty("promiseId")&&(console.warn(`Event '${e}' returned a promise. Consider using InvokeEventAsync instead.`),t.onEvent(`PromiseResolvedEvent:${n.promiseId}`,e=>{delete t.#r[`PromiseResolvedEvent:${n.promiseId}`]})),n}catch{return s}}static async InvokeEventAsync(e,n=void 0){return new Promise(s=>{const a=t.#o(e,n);try{const e=JSON.parse(a);e.hasOwnProperty("promiseId")?t.onEvent(`PromiseResolvedEvent:${e.promiseId}`,n=>{s(n),delete t.#r[`PromiseResolvedEvent:${e.promiseId}`]}):s(e)}catch{s(a)}})}static async WaitForEndOfFrameAsync(){return new Promise(e=>{const n=crypto.randomUUID().toString(),s=`EndOfFrameEvent:${n}`;t.onEvent(s,()=>{e(),delete t.#r[s]}),t.InvokeEvent("InstanceEvent:WaitForEndOfFrame",n)})}static async LoadSceneAsync(e){return new Promise(n=>{const s=`SceneLoadedEvent:${e}`;t.onEvent(s,()=>{n(),delete t.#r[s]}),t.InvokeEvent("InstanceEvent:LoadScene",e)})}static IsSceneLoading(){return t.InvokeEvent("InstanceEvent:IsSceneLoading")}static GetSceneLoadProgress(){return t.InvokeEvent("InstanceEvent:GetSceneLoadProgress")}static async LoadBundleAsync(e){await t.InvokeEventAsync("InstanceEvent:LoadBundle",e)}static async InstantiatePrefabFromBundleAsync(e,n,s=""){await t.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle",{bundleUrl:e,prefabName:n,parentKey:s})}static onInstanceReady(e){t.#s?e():t.#a.add(e)}static onEvent(e,n){t.#r.hasOwnProperty(e)||(t.#r[e]=new Set),t.#r[e].add(n)}static offEvent(e,n){t.#r.hasOwnProperty(e)&&t.#r[e].delete(n)}static#o(e,n){null==n&&(n="");let s=n;"object"==typeof n?s=JSON.stringify(n):"string"!=typeof n&&(s=n.toString());const a=t.#n(e,s);return t.#r[e]?.forEach(e=>e(s)),a}static _instanceReady(){t.#s=!0,t.#a.forEach(e=>e())}static _registerClientListener(e){t.#n=e}static _receiveEvent(e,n){let s=n;try{s=JSON.parse(n)}catch{}t.InvokeEvent(e,s)}static _logFromUnity(e,n){("internal"!==e||t.internalLogs)&&("error"===e?console.error(`[Unity] ${n}`):"warning"===e?console.warn(`[Unity] ${n}`):console.log(`[Unity] ${n}`))}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pizzapopcorn/unijs",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "A seamless interop layer to control Unity WebGL builds from the browser's JavaScript context.",
5
5
  "license": "MIT",
6
6
  "keywords": [