@pizzapopcorn/unijs 0.0.3 → 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,16 +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
- const { Unity } = require('./Unity');
94
135
  paramType = Unity.types[paramType] || paramType;
95
136
  this?.#invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
96
137
  }
97
138
 
139
+ /**
140
+ * Gets a child GameObject by index or name.
141
+ * @param {number | string} query
142
+ * @returns {GameObject | null}
143
+ */
98
144
  GetChild(query) {
99
145
  const eventName = typeof query === "string" ? "gameObject.findChild" : "gameObject.getChild";
100
146
  const childData = this?.#invokeGameObjectEvent(eventName, query);
@@ -106,26 +152,57 @@
106
152
  return null;
107
153
  }
108
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
+ */
109
161
  Translate(x, y, z) {
110
162
  this?.#invokeGameObjectEvent("transform.translate", { x: x, y: y, z: z });
111
163
  }
112
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
+ */
113
171
  Rotate(x, y, z) {
114
172
  this?.#invokeGameObjectEvent("transform.rotate", { x: x, y: y, z: z });
115
173
  }
116
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
+ */
117
181
  SetLocalScale(x, y, z) {
118
182
  this?.#invokeGameObjectEvent("transform.setLocalScale", { x: x, y: y, z: z });
119
183
  }
120
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
+ */
121
191
  SetLocalPosition(x, y, z) {
122
192
  this?.#invokeGameObjectEvent("transform.setLocalPosition", { x: x, y: y, z: z });
123
193
  }
124
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
+ */
125
199
  SetText(text) {
126
200
  this?.#invokeGameObjectEvent("text.setText", text);
127
201
  }
128
202
 
203
+ /**
204
+ * Destroys the GameObject.
205
+ */
129
206
  Destroy() {
130
207
  this?.#invokeGameObjectEvent("gameObject.destroy", "");
131
208
  }
@@ -137,11 +214,10 @@
137
214
  if(typeof payload === "object") payloadJson = JSON.stringify(payload);
138
215
  else if(typeof payload !== "string") payloadJson = payload.toString();
139
216
  const eventPayload = { eventName: eventName, hierarchyPath: this.hierarchyPath, payloadJson: payloadJson, listenDisabled: true };
140
-
141
- const { Unity } = require('./Unity');
217
+
142
218
  const response = Unity.InvokeEvent(`GOEvent:${this.key}`, JSON.stringify(eventPayload));
143
219
 
144
- console.log(`Invoked Event: GOEvent:${this.key}`, eventPayload);
220
+ if(Unity.internalLogs) console.log(`Invoked Event: GOEvent:${this.key}`, eventPayload);
145
221
 
146
222
  if(response === null || !response.hasOwnProperty("ok")){
147
223
  console.error(`Invalid JSON response from GameObject event callback: ${response}`);
@@ -160,7 +236,7 @@
160
236
  }
161
237
  }
162
238
 
163
- class Unity {
239
+ let Unity$1 = class Unity {
164
240
  /** @type {typeof GameObject} */
165
241
  static GameObject = GameObject;
166
242
  static internalLogs = false;
@@ -187,6 +263,11 @@
187
263
  static #onInstanceReadyListeners = new Set();
188
264
  static #onEventListeners = {};
189
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
+ */
190
271
  static LoadInstance(url, elementId) {
191
272
  Unity.#instanceReady = false;
192
273
  const r = new XMLHttpRequest();
@@ -201,14 +282,37 @@
201
282
  link.type = 'text/css';
202
283
  link.href = url + "/TemplateData/style.css";
203
284
  document.head.appendChild(link);
285
+
286
+ const indexScript = document.createElement("script");
287
+ indexScript.src = url + "/index.js";
288
+ document.body.appendChild(indexScript);
204
289
  };
205
290
  r.send();
206
291
  }
207
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
+ */
208
305
  static GetBuildVersion() {
209
306
  return Unity.InvokeEvent("InstanceEvent:GetBuildVersion");
210
307
  }
211
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
+ */
212
316
  static InvokeEvent(eventName, payload = undefined) {
213
317
  const responseJson = Unity.#invokeEventInternal(eventName, payload);
214
318
  try {
@@ -226,6 +330,13 @@
226
330
  }
227
331
  }
228
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
+ */
229
340
  static async InvokeEventAsync(eventName, payload = undefined) {
230
341
  return new Promise(resolve => {
231
342
  const responseJson = Unity.#invokeEventInternal(eventName, payload);
@@ -246,6 +357,10 @@
246
357
  })
247
358
  }
248
359
 
360
+ /**
361
+ * Awaits the Unity WaitForEndOfFrame coroutine.
362
+ * @returns {Promise<void>}
363
+ */
249
364
  static async WaitForEndOfFrameAsync() {
250
365
  return new Promise((resolve) => {
251
366
  const eventId = crypto.randomUUID().toString();
@@ -260,10 +375,56 @@
260
375
  });
261
376
  }
262
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
+ */
263
416
  static async LoadBundleAsync(bundleUrl) {
264
417
  await Unity.InvokeEventAsync("InstanceEvent:LoadBundle", bundleUrl);
265
418
  }
266
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
+ */
267
428
  static async InstantiatePrefabFromBundleAsync(bundleUrl, prefabName, parentKey = "") {
268
429
  await Unity.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle", {
269
430
  bundleUrl: bundleUrl,
@@ -274,6 +435,10 @@
274
435
 
275
436
  // Listeners -----------------------------
276
437
 
438
+ /**
439
+ * Registers a callback that will be invoked when the Unity instance is ready.
440
+ * @param {function} callback
441
+ */
277
442
  static onInstanceReady(callback) {
278
443
  if(!Unity.#instanceReady) {
279
444
  Unity.#onInstanceReadyListeners.add(callback);
@@ -283,6 +448,11 @@
283
448
  }
284
449
  }
285
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
+ */
286
456
  static onEvent(eventName, callback) {
287
457
  if(!Unity.#onEventListeners.hasOwnProperty(eventName)) {
288
458
  Unity.#onEventListeners[eventName] = new Set();
@@ -290,6 +460,11 @@
290
460
  Unity.#onEventListeners[eventName].add(callback);
291
461
  }
292
462
 
463
+ /**
464
+ * Unregisters a callback previously registered with onEvent.
465
+ * @param {string} eventName
466
+ * @param {function} callback
467
+ */
293
468
  static offEvent(eventName, callback) {
294
469
  if(!Unity.#onEventListeners.hasOwnProperty(eventName)) return;
295
470
  Unity.#onEventListeners[eventName].delete(callback);
@@ -336,8 +511,8 @@
336
511
  else console.log(`[Unity] ${message}`);
337
512
  }
338
513
 
339
- }
514
+ };
340
515
 
341
- return Unity;
516
+ return Unity$1;
342
517
 
343
518
  }));
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=""){const{Unity:s}=require("./Unity");t=s.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},{Unity:a}=require("./Unity"),r=a.InvokeEvent(`GOEvent:${this.key}`,JSON.stringify(s));if(console.log(`Invoked Event: GOEvent:${this.key}`,s),null===r||!r.hasOwnProperty("ok"))return console.error(`Invalid JSON response from GameObject event callback: ${r}`),null;if(r.ok){let e=r.responseJson;try{e=JSON.parse(r.responseJson)}catch{}return e}return console.error(`Error invoking GameObject event: ${e}`,r.error),null}}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)},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}`))}}return t});
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.3",
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": [