@pizzapopcorn/unijs 0.0.6 → 0.0.7

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
@@ -4,897 +4,910 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Unity = factory());
5
5
  })(this, (function () { 'use strict';
6
6
 
7
- class Transform {
8
-
9
- constructor(gameObject) {
10
- this.gameObject = gameObject;
11
- }
12
-
13
- /**
14
- * Gets the GameObject's world position.
15
- * @returns {object}
16
- */
17
- get position() {
18
- return this.#tryInvokeGameObjectEvent("transform.getPosition", "");
19
- }
20
-
21
- /**
22
- * Sets the GameObject's world position.
23
- * @param {object} value
24
- */
25
- set position(value) {
26
- this.#assertVector3(value);
27
- this.#tryInvokeGameObjectEvent("transform.setPosition", value);
28
- }
29
-
30
- /**
31
- * Gets the GameObject's local position.
32
- * @returns {object}
33
- */
34
- get localPosition() {
35
- return this.#tryInvokeGameObjectEvent("transform.getLocalPosition", "");
36
- }
37
-
38
- /**
39
- * Sets the GameObject's local position.
40
- * @param {object} value
41
- */
42
- set localPosition(value) {
43
- this.#assertVector3(value);
44
- this.#tryInvokeGameObjectEvent("transform.setLocalPosition", value);
45
- }
46
-
47
- /**
48
- * Gets the GameObject's local rotation.
49
- * @returns {object}
50
- */
51
- get rotation() {
52
- return this.#tryInvokeGameObjectEvent("transform.getRotation", "");
53
- }
54
-
55
- /**
56
- * Sets the GameObject's local rotation.
57
- * @param {object} value
58
- */
59
- set rotation(value) {
60
- this.#assertQuaternion(value);
61
- this.#tryInvokeGameObjectEvent("transform.setRotation", value);
62
- }
63
-
64
- /**
65
- * Gets the GameObject's euler angles in degrees.
66
- * @returns {object}
67
- */
68
- get eulerAngles() {
69
- return this.#tryInvokeGameObjectEvent("transform.getEulerAngles", "");
70
- }
71
-
72
- /**
73
- * Sets the GameObject's euler angles.
74
- * @param {object} value
75
- */
76
- set eulerAngles(value) {
77
- console.warn("[Unity] eulerAngles is read-only.");
78
- }
79
-
80
- /**
81
- * Gets the GameObject's local scale.
82
- * @returns {object}
83
- */
84
- get localScale() {
85
- return this.#tryInvokeGameObjectEvent("transform.getLocalScale", "");
86
- }
87
-
88
- /**
89
- * Sets the GameObject's local scale.
90
- * @param {object} value
91
- */
92
- set localScale(value) {
93
- this.#assertVector3(value);
94
- this.#tryInvokeGameObjectEvent("transform.setLocalScale", value);
95
- }
96
-
97
- /**
98
- * Gets the GameObject's lossy scale (Read Only).
99
- * @returns {object}
100
- */
101
- get lossyScale() {
102
- return this.#tryInvokeGameObjectEvent("transform.getLossyScale", "");
103
- }
104
-
105
- /**
106
- * Sets the GameObject's lossy scale.
107
- * @param {object} value
108
- */
109
- set lossyScale(value) {
110
- console.warn("[Unity] lossyScale is read-only.");
111
- }
112
-
113
- /**
114
- * Translates the GameObject's position by the specified amount on each axis.
115
- * @param {number} x
116
- * @param {number} y
117
- * @param {number} z
118
- */
119
- Translate(x, y, z) {
120
- this.#tryInvokeGameObjectEvent("transform.translate", { x: x, y: y, z: z });
121
- }
122
-
123
- /**
124
- * Rotates the GameObject around its local axis by the specified amount in degrees.
125
- * @param {number} x
126
- * @param {number} y
127
- * @param {number} z
128
- */
129
- Rotate(x, y, z) {
130
- this.#tryInvokeGameObjectEvent("transform.rotate", { x: x, y: y, z: z });
131
- }
132
-
133
-
134
- #tryInvokeGameObjectEvent(eventName, payload) {
135
- if(!this.gameObject) {
136
- console.error("[Unity] The GameObject associated with this Transform is null");
137
- }
138
- return this.gameObject._invokeGameObjectEvent(eventName, payload);
139
- }
140
-
141
- #assertVector3(value) {
142
- if (typeof value !== "object" || value === null || typeof value.x !== "number" || typeof value.y !== "number" || typeof value.z !== "number") {
143
- throw new Error(`[Unity] Invalid Vector3: ${JSON.stringify(value)}`);
144
- }
145
- }
146
-
147
- #assertQuaternion(value) {
148
- if (typeof value !== "object" || value === null || typeof value.x !== "number" || typeof value.y !== "number" || typeof value.z !== "number" || typeof value.w !== "number") {
149
- throw new Error(`[Unity] Invalid Quaternion: ${JSON.stringify(value)}`);
150
- }
151
- }
7
+ class Transform {
8
+
9
+ constructor(gameObject) {
10
+ this.gameObject = gameObject;
11
+ }
12
+
13
+ /**
14
+ * Gets the GameObject's world position.
15
+ * @returns {object}
16
+ */
17
+ get position() {
18
+ return this.#tryInvokeGameObjectEvent("transform.getPosition", "");
19
+ }
20
+
21
+ /**
22
+ * Sets the GameObject's world position.
23
+ * @param {object} value
24
+ */
25
+ set position(value) {
26
+ this.#assertVector3(value);
27
+ this.#tryInvokeGameObjectEvent("transform.setPosition", value);
28
+ }
29
+
30
+ /**
31
+ * Gets the GameObject's local position.
32
+ * @returns {object}
33
+ */
34
+ get localPosition() {
35
+ return this.#tryInvokeGameObjectEvent("transform.getLocalPosition", "");
36
+ }
37
+
38
+ /**
39
+ * Sets the GameObject's local position.
40
+ * @param {object} value
41
+ */
42
+ set localPosition(value) {
43
+ this.#assertVector3(value);
44
+ this.#tryInvokeGameObjectEvent("transform.setLocalPosition", value);
45
+ }
46
+
47
+ /**
48
+ * Gets the GameObject's local rotation.
49
+ * @returns {object}
50
+ */
51
+ get rotation() {
52
+ return this.#tryInvokeGameObjectEvent("transform.getRotation", "");
53
+ }
54
+
55
+ /**
56
+ * Sets the GameObject's local rotation.
57
+ * @param {object} value
58
+ */
59
+ set rotation(value) {
60
+ this.#assertQuaternion(value);
61
+ this.#tryInvokeGameObjectEvent("transform.setRotation", value);
62
+ }
63
+
64
+ /**
65
+ * Gets the GameObject's euler angles in degrees.
66
+ * @returns {object}
67
+ */
68
+ get eulerAngles() {
69
+ return this.#tryInvokeGameObjectEvent("transform.getEulerAngles", "");
70
+ }
71
+
72
+ /**
73
+ * Sets the GameObject's euler angles.
74
+ * @param {object} value
75
+ */
76
+ set eulerAngles(value) {
77
+ console.warn("[Unity] eulerAngles is read-only.");
78
+ }
79
+
80
+ /**
81
+ * Gets the GameObject's local scale.
82
+ * @returns {object}
83
+ */
84
+ get localScale() {
85
+ return this.#tryInvokeGameObjectEvent("transform.getLocalScale", "");
86
+ }
87
+
88
+ /**
89
+ * Sets the GameObject's local scale.
90
+ * @param {object} value
91
+ */
92
+ set localScale(value) {
93
+ this.#assertVector3(value);
94
+ this.#tryInvokeGameObjectEvent("transform.setLocalScale", value);
95
+ }
96
+
97
+ /**
98
+ * Gets the GameObject's lossy scale (Read Only).
99
+ * @returns {object}
100
+ */
101
+ get lossyScale() {
102
+ return this.#tryInvokeGameObjectEvent("transform.getLossyScale", "");
103
+ }
104
+
105
+ /**
106
+ * Sets the GameObject's lossy scale.
107
+ * @param {object} value
108
+ */
109
+ set lossyScale(value) {
110
+ console.warn("[Unity] lossyScale is read-only.");
111
+ }
112
+
113
+ /**
114
+ * Translates the GameObject's position by the specified amount on each axis.
115
+ * @param {number} x
116
+ * @param {number} y
117
+ * @param {number} z
118
+ */
119
+ Translate(x, y, z) {
120
+ this.#tryInvokeGameObjectEvent("transform.translate", { x: x, y: y, z: z });
121
+ }
122
+
123
+ /**
124
+ * Rotates the GameObject around its local axis by the specified amount in degrees.
125
+ * @param {number} x
126
+ * @param {number} y
127
+ * @param {number} z
128
+ */
129
+ Rotate(x, y, z) {
130
+ this.#tryInvokeGameObjectEvent("transform.rotate", { x: x, y: y, z: z });
131
+ }
132
+
133
+
134
+ #tryInvokeGameObjectEvent(eventName, payload) {
135
+ if(!this.gameObject) {
136
+ console.error("[Unity] The GameObject associated with this Transform is null");
137
+ }
138
+ return this.gameObject._invokeGameObjectEvent(eventName, payload);
139
+ }
140
+
141
+ #assertVector3(value) {
142
+ if (typeof value !== "object" || value === null || typeof value.x !== "number" || typeof value.y !== "number" || typeof value.z !== "number") {
143
+ throw new Error(`[Unity] Invalid Vector3: ${JSON.stringify(value)}`);
144
+ }
145
+ }
146
+
147
+ #assertQuaternion(value) {
148
+ if (typeof value !== "object" || value === null || typeof value.x !== "number" || typeof value.y !== "number" || typeof value.z !== "number" || typeof value.w !== "number") {
149
+ throw new Error(`[Unity] Invalid Quaternion: ${JSON.stringify(value)}`);
150
+ }
151
+ }
152
152
  }
153
153
 
154
- class Rigidbody {
155
-
156
- constructor(gameObject) {
157
- this.gameObject = gameObject;
158
- }
159
-
160
- /**
161
- * Gets the mass of the RigidBody.
162
- * @returns {number}
163
- */
164
- get mass() {
165
- return this.#tryInvokeGameObjectEvent("physics.getMass", "");
166
- }
167
-
168
- /**
169
- * Gets whether the RigidBody is affected by gravity.
170
- * @returns {boolean}
171
- */
172
- get useGravity() {
173
- return this.#tryInvokeGameObjectEvent("physics.getUseGravity", "");
174
- }
175
-
176
- /**
177
- * Gets whether the RigidBody is kinematic.
178
- * @returns {boolean}
179
- */
180
- get isKinematic() {
181
- return this.#tryInvokeGameObjectEvent("physics.getIsKinematic", "");
182
- }
183
-
184
- /**
185
- * Gets the linear damping of the RigidBody.
186
- * @returns {number}
187
- */
188
- get linearDamping() {
189
- return this.#tryInvokeGameObjectEvent("physics.getLinearDamping", "");
190
- }
191
-
192
- /**
193
- * Gets the angular damping of the RigidBody.
194
- * @returns {number}
195
- */
196
- get angularDamping() {
197
- return this.#tryInvokeGameObjectEvent("physics.getAngularDamping", "");
198
- }
199
-
200
- /**
201
- * Adds a force to the RigidBody.
202
- * @param {number} x
203
- * @param {number} y
204
- * @param {number} z
205
- */
206
- AddForce(x, y, z) {
207
- this.#tryInvokeGameObjectEvent("physics.addForce", { x: x, y: y, z: z });
208
- }
209
-
210
- /**
211
- * Adds a torque to the RigidBody.
212
- * @param {number} x
213
- * @param {number} y
214
- * @param {number} z
215
- */
216
- AddTorque(x, y, z) {
217
- this.#tryInvokeGameObjectEvent("physics.addTorque", { x: x, y: y, z: z });
218
- }
219
-
220
- /**
221
- * Sets the linear velocity of the RigidBody.
222
- * @param {number} x
223
- * @param {number} y
224
- * @param {number} z
225
- */
226
- SetVelocity(x, y, z) {
227
- this.#tryInvokeGameObjectEvent("physics.setVelocity", { x: x, y: y, z: z });
228
- }
229
-
230
- /**
231
- * Gets the linear velocity of the RigidBody.
232
- * @returns {object}
233
- */
234
- GetVelocity() {
235
- return this.#tryInvokeGameObjectEvent("physics.getVelocity", "");
236
- }
237
-
238
- /**
239
- * Sets the angular velocity of the RigidBody.
240
- * @param {number} x
241
- * @param {number} y
242
- * @param {number} z
243
- */
244
- SetAngularVelocity(x, y, z) {
245
- this.#tryInvokeGameObjectEvent("physics.setAngularVelocity", { x: x, y: y, z: z });
246
- }
247
-
248
- /**
249
- * Gets the angular velocity of the RigidBody.
250
- * @returns {object}
251
- */
252
- GetAngularVelocity() {
253
- return this.#tryInvokeGameObjectEvent("physics.getAngularVelocity", "");
254
- }
255
-
256
- /**
257
- * Sets whether the RigidBody is affected by gravity.
258
- * @param {boolean} useGravity
259
- */
260
- SetUseGravity(useGravity) {
261
- this.#tryInvokeGameObjectEvent("physics.setUseGravity", useGravity);
262
- }
263
-
264
- /**
265
- * Sets whether the RigidBody is kinematic.
266
- * @param {boolean} isKinematic
267
- */
268
- SetIsKinematic(isKinematic) {
269
- this.#tryInvokeGameObjectEvent("physics.setIsKinematic", isKinematic);
270
- }
271
-
272
- /**
273
- * Sets the mass of the RigidBody.
274
- * @param {number} mass
275
- */
276
- SetMass(mass) {
277
- this.#tryInvokeGameObjectEvent("physics.setMass", mass);
278
- }
279
-
280
- /**
281
- * Sets the linear damping of the RigidBody.
282
- * @param {number} linearDamping
283
- */
284
- SetLinearDamping(linearDamping) {
285
- this.#tryInvokeGameObjectEvent("physics.setLinearDamping", linearDamping);
286
- }
287
-
288
- #tryInvokeGameObjectEvent(eventName, payload) {
289
- if(!this.gameObject) {
290
- console.error("[Unity] The GameObject associated with this RigidBody is null");
291
- return null;
292
- }
293
- return this.gameObject._invokeGameObjectEvent(eventName, payload);
294
- }
154
+ class Rigidbody {
155
+
156
+ constructor(gameObject) {
157
+ this.gameObject = gameObject;
158
+ }
159
+
160
+ /**
161
+ * Gets the mass of the RigidBody.
162
+ * @returns {number}
163
+ */
164
+ get mass() {
165
+ return this.#tryInvokeGameObjectEvent("physics.getMass", "");
166
+ }
167
+
168
+ /**
169
+ * Gets whether the RigidBody is affected by gravity.
170
+ * @returns {boolean}
171
+ */
172
+ get useGravity() {
173
+ return this.#tryInvokeGameObjectEvent("physics.getUseGravity", "");
174
+ }
175
+
176
+ /**
177
+ * Gets whether the RigidBody is kinematic.
178
+ * @returns {boolean}
179
+ */
180
+ get isKinematic() {
181
+ return this.#tryInvokeGameObjectEvent("physics.getIsKinematic", "");
182
+ }
183
+
184
+ /**
185
+ * Gets the linear damping of the RigidBody.
186
+ * @returns {number}
187
+ */
188
+ get linearDamping() {
189
+ return this.#tryInvokeGameObjectEvent("physics.getLinearDamping", "");
190
+ }
191
+
192
+ /**
193
+ * Gets the angular damping of the RigidBody.
194
+ * @returns {number}
195
+ */
196
+ get angularDamping() {
197
+ return this.#tryInvokeGameObjectEvent("physics.getAngularDamping", "");
198
+ }
199
+
200
+ /**
201
+ * Adds a force to the RigidBody.
202
+ * @param {number} x
203
+ * @param {number} y
204
+ * @param {number} z
205
+ */
206
+ AddForce(x, y, z) {
207
+ this.#tryInvokeGameObjectEvent("physics.addForce", { x: x, y: y, z: z });
208
+ }
209
+
210
+ /**
211
+ * Adds a torque to the RigidBody.
212
+ * @param {number} x
213
+ * @param {number} y
214
+ * @param {number} z
215
+ */
216
+ AddTorque(x, y, z) {
217
+ this.#tryInvokeGameObjectEvent("physics.addTorque", { x: x, y: y, z: z });
218
+ }
219
+
220
+ /**
221
+ * Sets the linear velocity of the RigidBody.
222
+ * @param {number} x
223
+ * @param {number} y
224
+ * @param {number} z
225
+ */
226
+ SetVelocity(x, y, z) {
227
+ this.#tryInvokeGameObjectEvent("physics.setVelocity", { x: x, y: y, z: z });
228
+ }
229
+
230
+ /**
231
+ * Gets the linear velocity of the RigidBody.
232
+ * @returns {object}
233
+ */
234
+ GetVelocity() {
235
+ return this.#tryInvokeGameObjectEvent("physics.getVelocity", "");
236
+ }
237
+
238
+ /**
239
+ * Sets the angular velocity of the RigidBody.
240
+ * @param {number} x
241
+ * @param {number} y
242
+ * @param {number} z
243
+ */
244
+ SetAngularVelocity(x, y, z) {
245
+ this.#tryInvokeGameObjectEvent("physics.setAngularVelocity", { x: x, y: y, z: z });
246
+ }
247
+
248
+ /**
249
+ * Gets the angular velocity of the RigidBody.
250
+ * @returns {object}
251
+ */
252
+ GetAngularVelocity() {
253
+ return this.#tryInvokeGameObjectEvent("physics.getAngularVelocity", "");
254
+ }
255
+
256
+ /**
257
+ * Sets whether the RigidBody is affected by gravity.
258
+ * @param {boolean} useGravity
259
+ */
260
+ SetUseGravity(useGravity) {
261
+ this.#tryInvokeGameObjectEvent("physics.setUseGravity", useGravity);
262
+ }
263
+
264
+ /**
265
+ * Sets whether the RigidBody is kinematic.
266
+ * @param {boolean} isKinematic
267
+ */
268
+ SetIsKinematic(isKinematic) {
269
+ this.#tryInvokeGameObjectEvent("physics.setIsKinematic", isKinematic);
270
+ }
271
+
272
+ /**
273
+ * Sets the mass of the RigidBody.
274
+ * @param {number} mass
275
+ */
276
+ SetMass(mass) {
277
+ this.#tryInvokeGameObjectEvent("physics.setMass", mass);
278
+ }
279
+
280
+ /**
281
+ * Sets the linear damping of the RigidBody.
282
+ * @param {number} linearDamping
283
+ */
284
+ SetLinearDamping(linearDamping) {
285
+ this.#tryInvokeGameObjectEvent("physics.setLinearDamping", linearDamping);
286
+ }
287
+
288
+ #tryInvokeGameObjectEvent(eventName, payload) {
289
+ if(!this.gameObject) {
290
+ console.error("[Unity] The GameObject associated with this RigidBody is null");
291
+ return null;
292
+ }
293
+ return this.gameObject._invokeGameObjectEvent(eventName, payload);
294
+ }
295
295
  }
296
296
 
297
- class GameObject {
298
- #transform = null;
299
- #rigidbody = null;
300
-
301
- static keyGameObjects = {};
302
- static #lifeCycleCallbacks = {
303
- awake: {},
304
- start: {},
305
- update: {},
306
- enable: {},
307
- disable: {},
308
- destroy: {}
309
- }
310
-
311
- /**
312
- * Gets a GameObject by its JS Key (previously set in Unity using the JSKeyGameObject component).
313
- * @param {string} key
314
- * @returns {GameObject | null}
315
- * @constructor
316
- */
317
- static GetKeyGameObject(key){
318
- if(!GameObject.keyGameObjects.hasOwnProperty(key)) {
319
- console.error(`GameObject with key '${key}' not found`);
320
- return null;
321
- }
322
- return GameObject.keyGameObjects[key];
323
- }
324
-
325
- /**
326
- * Instantiates a prefab at the specified position and rotation either in world space or relative to a parent GameObject.
327
- * @param {string} prefabPath - The path to the prefab to instantiate from a Resources folder.
328
- * @param {Object} position - The position to instantiate the prefab at (Defaults to Vector3.Zero).
329
- * @param {Object} rotation - The rotation to instantiate the prefab with (Defaults to Quaternion.Identity).
330
- * @param {GameObject | Transform | null} parent - The parent GameObject to instantiate the prefab relative to (Defaults to null).
331
- */
332
- static Instantiate(prefabPath, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0, w: 1 }, parent = null) {
333
- if(parent === null){
334
- Unity.InvokeEvent("InstanceEvent:InstantiateGameObject", { prefabPath: prefabPath, position: position, rotation: rotation });
335
- }
336
- else {
337
- const p = parent instanceof GameObject ? parent : parent instanceof Transform ? parent.gameObject : null;
338
- if(p === null) return;
339
- p.Instantiate(prefabPath, position, rotation);
340
- }
341
- }
342
-
343
- /**
344
- * 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.
345
- * @param {string} key
346
- * @param {function} callback
347
- */
348
- static onAwake(key, callback){
349
- if(!GameObject.#lifeCycleCallbacks.awake.hasOwnProperty(key)) {
350
- GameObject.#lifeCycleCallbacks.awake[key] = new Set();
351
- }
352
- GameObject.#lifeCycleCallbacks.awake[key].add(callback);
353
- }
354
-
355
- /**
356
- * 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.
357
- * @param {string} key
358
- * @param {function} callback
359
- */
360
- static onStart(key, callback) {
361
- if(!GameObject.#lifeCycleCallbacks.start.hasOwnProperty(key)) {
362
- GameObject.#lifeCycleCallbacks.start[key] = new Set();
363
- }
364
- GameObject.#lifeCycleCallbacks.start[key].add(callback);
365
- }
366
-
367
- /**
368
- * Registers a callback for a GameObject's Update event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created.
369
- * @param {string} key
370
- * @param {function} callback
371
- */
372
- static onUpdate(key, callback) {
373
- if(!GameObject.#lifeCycleCallbacks.update.hasOwnProperty(key)) {
374
- GameObject.#lifeCycleCallbacks.update[key] = new Set();
375
- }
376
- GameObject.#lifeCycleCallbacks.update[key].add(callback);
377
- }
378
-
379
- /**
380
- * 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.
381
- * @param {string} key
382
- * @param {function} callback
383
- */
384
- static onEnable(key, callback) {
385
- if(!GameObject.#lifeCycleCallbacks.enable.hasOwnProperty(key)) {
386
- GameObject.#lifeCycleCallbacks.enable[key] = new Set();
387
- }
388
- GameObject.#lifeCycleCallbacks.enable[key].add(callback);
389
- }
390
-
391
- /**
392
- * 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.
393
- * @param {string} key
394
- * @param {function} callback
395
- */
396
- static onDisable(key, callback) {
397
- if(!GameObject.#lifeCycleCallbacks.disable.hasOwnProperty(key)) {
398
- GameObject.#lifeCycleCallbacks.disable[key] = new Set();
399
- }
400
- GameObject.#lifeCycleCallbacks.disable[key].add(callback);
401
- }
402
-
403
- /**
404
- * 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.
405
- * @param {string} key
406
- * @param {function} callback
407
- */
408
- static onDestroy(key, callback) {
409
- if(!GameObject.#lifeCycleCallbacks.destroy.hasOwnProperty(key)) {
410
- GameObject.#lifeCycleCallbacks.destroy[key] = new Set();
411
- }
412
- GameObject.#lifeCycleCallbacks.destroy[key].add(callback);
413
- }
414
-
415
- /**Only for unity js library use*/
416
- static _register(key, data) {
417
- GameObject.keyGameObjects[key] = new GameObject(key, data);
418
- }
419
-
420
- /**Only for unity js library use*/
421
- static _receiveLifeCycleEvent(key, event) {
422
- const gameObject = GameObject.keyGameObjects[key];
423
- if(!gameObject) return;
424
-
425
- const callbacks = GameObject.#lifeCycleCallbacks[event][key];
426
- if(callbacks) {
427
- for(const callback of callbacks) {
428
- callback(gameObject);
429
- }
430
- }
431
- if(event === "destroy") {
432
- delete GameObject.keyGameObjects[key];
433
- }
434
- }
435
-
436
- constructor(key, data) {
437
- this.key = key;
438
- this.name = data.name;
439
- this.#transform = new Transform(this);
440
- if(data.hasRigidbody) {
441
- this.#rigidbody = new Rigidbody(this);
442
- }
443
- this.hierarchyPath = data.hasOwnProperty("hierarchyPath") ? data.hierarchyPath : "";
444
- }
445
-
446
- /**
447
- * Gets the Transform component of the GameObject.
448
- * @returns {Transform}
449
- */
450
- get transform() {
451
- return this.#transform;
452
- }
453
-
454
- /**
455
- * Gets the RigidBody component of the GameObject.
456
- * @returns {Rigidbody | null}
457
- */
458
- get rigidbody() {
459
- if(this.HasComponent("Rigidbody")) {
460
- this.#rigidbody = new Rigidbody(this);
461
- return this.#rigidbody;
462
- }
463
- return null;
464
- }
465
-
466
- /**
467
- * Sets the GameObject's active state.
468
- * @param {boolean} active
469
- */
470
- SetActive(active) {
471
- this?._invokeGameObjectEvent("gameObject.setActive", active);
472
- }
473
-
474
- /**
475
- * Invokes a method on the GameObject via SendMessage. Use GameObject.types for type options.
476
- * <br>In order for it to work with custom types, you need to get the fully qualified name of the type.
477
- * @param {string} methodName
478
- * @param {string} paramType
479
- * @param {string} paramValue
480
- */
481
- InvokeMethod(methodName, paramType = "", paramValue = "") {
482
- paramType = Unity.types[paramType] || paramType;
483
- this?._invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
484
- }
485
-
486
- /**
487
- * Gets a child GameObject by index or name.
488
- * @param {number | string} query
489
- * @returns {GameObject | null}
490
- */
491
- GetChild(query) {
492
- const eventName = typeof query === "string" ? "gameObject.findChild" : "gameObject.getChild";
493
- const childData = this?._invokeGameObjectEvent(eventName, query);
494
- if(childData !== null) {
495
- const currentPath = this.hierarchyPath === "" ? this.key : this.hierarchyPath;
496
- childData.hierarchyPath = currentPath + "/" + childData.name;
497
- return new GameObject(this.key, childData);
498
- }
499
- return null;
500
- }
501
-
502
- /**
503
- * Looks for a text component and sets its text to the specified value. It works with Legacy, TextMeshPro, and TextMesh components.
504
- * @param {string} text
505
- */
506
- SetText(text) {
507
- this?._invokeGameObjectEvent("text.setText", text);
508
- }
509
-
510
- /**
511
- * Destroys the GameObject.
512
- */
513
- Destroy() {
514
- this?._invokeGameObjectEvent("gameObject.destroy", "");
515
- }
516
-
517
- /**
518
- * Instantiates a prefab at the specified position and rotation relative to this GameObject's transform.
519
- * @param {string} prefabPath - The path to the prefab to instantiate from a Resources folder.
520
- * @param {Object} position - The position to instantiate the prefab at (Defaults to Vector3.Zero).
521
- * @param {Object} rotation - The rotation to instantiate the prefab with (Defaults to Quaternion.Identity).
522
- */
523
- Instantiate(prefabPath, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0, w: 1 }) {
524
- this?._invokeGameObjectEvent("gameObject.instantiate", { prefabPath: prefabPath, position: position, rotation: rotation });
525
- }
526
-
527
- HasComponent(componentName) {
528
- return this?._invokeGameObjectEvent("gameObject.hasComponent", componentName);
529
- }
530
-
531
- GetComponent(componentName) {
532
- return this?._invokeGameObjectEvent("gameObject.getComponent", componentName);
533
- }
534
-
535
- AddComponent(componentName) {
536
- return this?._invokeGameObjectEvent("gameObject.addComponent", componentName);
537
- }
538
-
539
- /**Only for internal library use*/
540
- _invokeGameObjectEvent(eventName, payload) {
541
- let payloadJson = payload;
542
- if(typeof payload === "object") payloadJson = JSON.stringify(payload);
543
- else if(typeof payload !== "string") payloadJson = payload.toString();
544
- const eventPayload = { eventName: eventName, hierarchyPath: this.hierarchyPath, payloadJson: payloadJson, listenDisabled: true };
545
-
546
- const response = Unity.InvokeEvent(`GOEvent:${this.key}`, JSON.stringify(eventPayload));
547
-
548
- if(Unity.internalLogs) console.log(`Invoked Event: GOEvent:${this.key}`, eventPayload);
549
-
550
- if(response === null || !response.hasOwnProperty("ok")){
551
- console.error(`Invalid JSON response from GameObject event callback: ${response}`);
552
- return null;
553
- }
554
-
555
- if(response.ok) {
556
- let responseObj = response.responseJson;
557
- try {
558
- responseObj = JSON.parse(response.responseJson);
559
- } catch {}
560
- return responseObj;
561
- }
562
- console.error(`Error invoking GameObject event: ${eventName}`, response.error);
563
- return null;
564
- }
297
+ class GameObject {
298
+ #transform = null;
299
+ #rigidbody = null;
300
+ #rootInstance = null;
301
+
302
+ static keyGameObjects = {};
303
+ static #lifeCycleCallbacks = {
304
+ awake: {},
305
+ start: {},
306
+ update: {},
307
+ enable: {},
308
+ disable: {},
309
+ destroy: {}
310
+ }
311
+
312
+ /**
313
+ * Gets a GameObject by its JS Key (previously set in Unity using the JSKeyGameObject component).
314
+ * @param {string} key
315
+ * @returns {GameObject | null}
316
+ * @constructor
317
+ */
318
+ static GetKeyGameObject(key){
319
+ if(!GameObject.keyGameObjects.hasOwnProperty(key)) {
320
+ const data = Unity.InvokeEvent("InstanceEvent:GetKeyGameObject", key);
321
+ if(data) {
322
+ GameObject.keyGameObjects[key] = new GameObject(key, data);
323
+ }
324
+ else {
325
+ console.error(`GameObject with key '${key}' not found`);
326
+ return null;
327
+ }
328
+ }
329
+ return GameObject.keyGameObjects[key];
330
+ }
331
+
332
+ /**
333
+ * Instantiates a prefab at the specified position and rotation either in world space or relative to a parent GameObject.
334
+ * @param {string} prefabPath - The path to the prefab to instantiate from a Resources folder.
335
+ * @param {Object} position - The position to instantiate the prefab at (Defaults to Vector3.Zero).
336
+ * @param {Object} rotation - The rotation to instantiate the prefab with (Defaults to Quaternion.Identity).
337
+ * @param {GameObject | Transform | null} parent - The parent GameObject to instantiate the prefab relative to (Defaults to null).
338
+ */
339
+ static Instantiate(prefabPath, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0, w: 1 }, parent = null) {
340
+ if(parent === null){
341
+ Unity.InvokeEvent("InstanceEvent:InstantiateGameObject", { prefabPath: prefabPath, position: position, rotation: rotation });
342
+ }
343
+ else {
344
+ const p = parent instanceof GameObject ? parent : parent instanceof Transform ? parent.gameObject : null;
345
+ if(p === null) return;
346
+ p.Instantiate(prefabPath, position, rotation);
347
+ }
348
+ }
349
+
350
+ /**
351
+ * 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.
352
+ * @param {string} key
353
+ * @param {function} callback
354
+ */
355
+ static onAwake(key, callback){
356
+ if(!GameObject.#lifeCycleCallbacks.awake.hasOwnProperty(key)) {
357
+ GameObject.#lifeCycleCallbacks.awake[key] = new Set();
358
+ }
359
+ GameObject.#lifeCycleCallbacks.awake[key].add(callback);
360
+ }
361
+
362
+ /**
363
+ * 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.
364
+ * @param {string} key
365
+ * @param {function} callback
366
+ */
367
+ static onStart(key, callback) {
368
+ if(!GameObject.#lifeCycleCallbacks.start.hasOwnProperty(key)) {
369
+ GameObject.#lifeCycleCallbacks.start[key] = new Set();
370
+ }
371
+ GameObject.#lifeCycleCallbacks.start[key].add(callback);
372
+ }
373
+
374
+ /**
375
+ * Registers a callback for a GameObject's Update event using its JS Key. If the GameObject doesn't exist yet, it will trigger when it's created.
376
+ * @param {string} key
377
+ * @param {function} callback
378
+ */
379
+ static onUpdate(key, callback) {
380
+ if(!GameObject.#lifeCycleCallbacks.update.hasOwnProperty(key)) {
381
+ GameObject.#lifeCycleCallbacks.update[key] = new Set();
382
+ }
383
+ GameObject.#lifeCycleCallbacks.update[key].add(callback);
384
+ }
385
+
386
+ /**
387
+ * 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.
388
+ * @param {string} key
389
+ * @param {function} callback
390
+ */
391
+ static onEnable(key, callback) {
392
+ if(!GameObject.#lifeCycleCallbacks.enable.hasOwnProperty(key)) {
393
+ GameObject.#lifeCycleCallbacks.enable[key] = new Set();
394
+ }
395
+ GameObject.#lifeCycleCallbacks.enable[key].add(callback);
396
+ }
397
+
398
+ /**
399
+ * 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.
400
+ * @param {string} key
401
+ * @param {function} callback
402
+ */
403
+ static onDisable(key, callback) {
404
+ if(!GameObject.#lifeCycleCallbacks.disable.hasOwnProperty(key)) {
405
+ GameObject.#lifeCycleCallbacks.disable[key] = new Set();
406
+ }
407
+ GameObject.#lifeCycleCallbacks.disable[key].add(callback);
408
+ }
409
+
410
+ /**
411
+ * 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.
412
+ * @param {string} key
413
+ * @param {function} callback
414
+ */
415
+ static onDestroy(key, callback) {
416
+ if(!GameObject.#lifeCycleCallbacks.destroy.hasOwnProperty(key)) {
417
+ GameObject.#lifeCycleCallbacks.destroy[key] = new Set();
418
+ }
419
+ GameObject.#lifeCycleCallbacks.destroy[key].add(callback);
420
+ }
421
+
422
+ /**Only for unity js library use*/
423
+ static _register(key, data) {
424
+ GameObject.keyGameObjects[key] = new GameObject(key, data);
425
+ }
426
+
427
+ /**Only for unity js library use*/
428
+ static _receiveLifeCycleEvent(key, event) {
429
+ const gameObject = GameObject.keyGameObjects[key];
430
+ if(!gameObject) return;
431
+
432
+ const callbacks = GameObject.#lifeCycleCallbacks[event][key];
433
+ if(callbacks) {
434
+ for(const callback of callbacks) {
435
+ callback(gameObject);
436
+ }
437
+ }
438
+ if(event === "destroy") {
439
+ delete GameObject.keyGameObjects[key];
440
+ }
441
+ }
442
+
443
+ constructor(key, data, root = null) {
444
+ this.key = key;
445
+ this.name = data.name;
446
+ this.#rootInstance = root || this;
447
+ this.#transform = new Transform(this);
448
+ if(data.hasRigidbody) {
449
+ this.#rigidbody = new Rigidbody(this);
450
+ }
451
+ this.hierarchyPath = data.hasOwnProperty("hierarchyPath") ? data.hierarchyPath : "";
452
+ }
453
+
454
+ /**
455
+ * Gets the Transform component of the GameObject.
456
+ * @returns {Transform}
457
+ */
458
+ get transform() {
459
+ return this.#transform;
460
+ }
461
+
462
+ /**
463
+ * Gets the RigidBody component of the GameObject.
464
+ * @returns {Rigidbody | null}
465
+ */
466
+ get rigidbody() {
467
+ if(this.HasComponent("Rigidbody")) {
468
+ this.#rigidbody = new Rigidbody(this);
469
+ return this.#rigidbody;
470
+ }
471
+ return null;
472
+ }
473
+
474
+ /**
475
+ * Sets the GameObject's active state.
476
+ * @param {boolean} active
477
+ */
478
+ SetActive(active) {
479
+ this?._invokeGameObjectEvent("gameObject.setActive", active);
480
+ }
481
+
482
+ /**
483
+ * Invokes a method on the GameObject via SendMessage. Use GameObject.types for type options.
484
+ * <br>In order for it to work with custom types, you need to get the fully qualified name of the type.
485
+ * @param {string} methodName
486
+ * @param {string} paramType
487
+ * @param {string} paramValue
488
+ */
489
+ InvokeMethod(methodName, paramType = "", paramValue = "") {
490
+ paramType = Unity.types[paramType] || paramType;
491
+ this?._invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
492
+ }
493
+
494
+ /**
495
+ * Gets a child GameObject by index or name.
496
+ * @param {number | string} query
497
+ * @returns {GameObject | null}
498
+ */
499
+ GetChild(query) {
500
+ const eventName = typeof query === "string" ? "gameObject.findChild" : "gameObject.getChild";
501
+ const childData = this?._invokeGameObjectEvent(eventName, query);
502
+ if(childData !== null) {
503
+ const currentPath = this.hierarchyPath === "" ? this.key : this.hierarchyPath;
504
+ childData.hierarchyPath = currentPath + "/" + childData.name;
505
+ return new GameObject(this.key, childData, this.#rootInstance);
506
+ }
507
+ return null;
508
+ }
509
+
510
+ /**
511
+ * Looks for a text component and sets its text to the specified value. It works with Legacy, TextMeshPro, and TextMesh components.
512
+ * @param {string} text
513
+ */
514
+ SetText(text) {
515
+ this?._invokeGameObjectEvent("text.setText", text);
516
+ }
517
+
518
+ /**
519
+ * Destroys the GameObject.
520
+ */
521
+ Destroy() {
522
+ this?._invokeGameObjectEvent("gameObject.destroy", "");
523
+ }
524
+
525
+ /**
526
+ * Instantiates a prefab at the specified position and rotation relative to this GameObject's transform.
527
+ * @param {string} prefabPath - The path to the prefab to instantiate from a Resources folder.
528
+ * @param {Object} position - The position to instantiate the prefab at (Defaults to Vector3.Zero).
529
+ * @param {Object} rotation - The rotation to instantiate the prefab with (Defaults to Quaternion.Identity).
530
+ */
531
+ Instantiate(prefabPath, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0, w: 1 }) {
532
+ this?._invokeGameObjectEvent("gameObject.instantiate", { prefabPath: prefabPath, position: position, rotation: rotation });
533
+ }
534
+
535
+ HasComponent(componentName) {
536
+ return this?._invokeGameObjectEvent("gameObject.hasComponent", componentName);
537
+ }
538
+
539
+ GetComponent(componentName) {
540
+ return this?._invokeGameObjectEvent("gameObject.getComponent", componentName);
541
+ }
542
+
543
+ AddComponent(componentName) {
544
+ return this?._invokeGameObjectEvent("gameObject.addComponent", componentName);
545
+ }
546
+
547
+ /**Only for internal library use*/
548
+ _invokeGameObjectEvent(eventName, payload) {
549
+ if(GameObject.keyGameObjects[this.key] !== this.#rootInstance) {
550
+ console.error(`Attempted to invoke event '${eventName}' on a stale GameObject reference (Key: ${this.key}, Path: ${this.hierarchyPath}). This object has been destroyed or replaced.`);
551
+ return null;
552
+ }
553
+
554
+ let payloadJson = payload;
555
+ if(typeof payload === "object") payloadJson = JSON.stringify(payload);
556
+ else if(typeof payload !== "string") payloadJson = payload.toString();
557
+ const eventPayload = { eventName: eventName, hierarchyPath: this.hierarchyPath, payloadJson: payloadJson, listenDisabled: true };
558
+
559
+ const response = Unity.InvokeEvent(`GOEvent:${this.key}`, JSON.stringify(eventPayload));
560
+
561
+ if(Unity.internalLogs) console.log(`Invoked Event: GOEvent:${this.key}`, eventPayload);
562
+
563
+ if(response === null || !response.hasOwnProperty("ok")){
564
+ console.error(`Invalid JSON response from GameObject event callback: ${response}`);
565
+ return null;
566
+ }
567
+
568
+ if(response.ok) {
569
+ let responseObj = response.responseJson;
570
+ try {
571
+ responseObj = JSON.parse(response.responseJson);
572
+ } catch {}
573
+ return responseObj;
574
+ }
575
+ console.error(`Error invoking GameObject event: ${eventName}`, response.error);
576
+ return null;
577
+ }
565
578
  }
566
579
 
567
- class Time {
568
- /**
569
- * Current time in seconds.
570
- * @returns {number}
571
- */
572
- static get time() {
573
- return Unity.InvokeEvent("InstanceEvent:GetTime");
574
- }
575
-
576
- /**
577
- * The time since the last frame in seconds.
578
- * @returns {number}
579
- */
580
- static get deltaTime() {
581
- return Unity.InvokeEvent("InstanceEvent:GetDeltaTime");
582
- }
583
-
584
- /**
585
- * The interval in seconds of in-game time at which physics and other fixed frame rate updates (like MonoBehaviour's MonoBehaviour.FixedUpdate) are performed.
586
- * @returns {number}
587
- */
588
- static get fixedDeltaTime() {
589
- return Unity.InvokeEvent("InstanceEvent:GetFixedDeltaTime");
590
- }
591
-
592
- /**
593
- * The timeScale-independent interval in seconds from the last frame to the current one
594
- * @returns {number}
595
- */
596
- static get unscaledDeltaTime() {
597
- return Unity.InvokeEvent("InstanceEvent:GetUnscaledDeltaTime");
598
- }
599
-
600
- /**
601
- * The real time in seconds since Unity started running.
602
- * @returns {number}
603
- */
604
- static get realtimeSinceStartup() {
605
- return Unity.InvokeEvent("InstanceEvent:GetRealtimeSinceStartup");
606
- }
607
-
608
- /**
609
- * The scale at which time passes.
610
- * @returns {number}
611
- */
612
- static get timeScale() {
613
- return Unity.InvokeEvent("InstanceEvent:GetTimeScale");
614
- }
615
-
616
- static set timeScale(value) {
617
- Unity.InvokeEvent("InstanceEvent:SetTimeScale", value);
618
- }
580
+ class Time {
581
+ /**
582
+ * Current time in seconds.
583
+ * @returns {number}
584
+ */
585
+ static get time() {
586
+ return Unity.InvokeEvent("InstanceEvent:GetTime");
587
+ }
588
+
589
+ /**
590
+ * The time since the last frame in seconds.
591
+ * @returns {number}
592
+ */
593
+ static get deltaTime() {
594
+ return Unity.InvokeEvent("InstanceEvent:GetDeltaTime");
595
+ }
596
+
597
+ /**
598
+ * The interval in seconds of in-game time at which physics and other fixed frame rate updates (like MonoBehaviour's MonoBehaviour.FixedUpdate) are performed.
599
+ * @returns {number}
600
+ */
601
+ static get fixedDeltaTime() {
602
+ return Unity.InvokeEvent("InstanceEvent:GetFixedDeltaTime");
603
+ }
604
+
605
+ /**
606
+ * The timeScale-independent interval in seconds from the last frame to the current one
607
+ * @returns {number}
608
+ */
609
+ static get unscaledDeltaTime() {
610
+ return Unity.InvokeEvent("InstanceEvent:GetUnscaledDeltaTime");
611
+ }
612
+
613
+ /**
614
+ * The real time in seconds since Unity started running.
615
+ * @returns {number}
616
+ */
617
+ static get realtimeSinceStartup() {
618
+ return Unity.InvokeEvent("InstanceEvent:GetRealtimeSinceStartup");
619
+ }
620
+
621
+ /**
622
+ * The scale at which time passes.
623
+ * @returns {number}
624
+ */
625
+ static get timeScale() {
626
+ return Unity.InvokeEvent("InstanceEvent:GetTimeScale");
627
+ }
628
+
629
+ static set timeScale(value) {
630
+ Unity.InvokeEvent("InstanceEvent:SetTimeScale", value);
631
+ }
619
632
  }
620
633
 
621
- let Unity$1 = class Unity {
622
- /** @type {typeof GameObject} */
623
- static GameObject = GameObject;
624
- /** @type {typeof Time} */
625
- static Time = Time;
626
- static internalLogs = false;
627
- static types = {
628
- int: "System.Int32",
629
- float: "System.Single",
630
- double: "System.Double",
631
- bool: "System.Boolean",
632
- string: "System.String",
633
- char: "System.Char",
634
- byte: "System.Byte",
635
- long: "System.Int64",
636
- short: "System.Int16",
637
- decimal: "System.Decimal",
638
- object: "System.Object",
639
- customClass: (className, namespace = "", assembly = "Assembly-CSharp") => {
640
- const qualifiedName = namespace === "" ? className : `${namespace}.${className}`;
641
- return `${qualifiedName}, ${assembly}.dll`;
642
- },
643
- };
644
-
645
- static #clientEventCallback;
646
- static #instanceReady = false;
647
- static #onInstanceReadyListeners = new Set();
648
- static #onEventListeners = {};
649
-
650
- /**
651
- * Loads the Unity canvas from the specified URL and injects it into the specified element.
652
- * @param {string} url
653
- * @param {string} elementId
654
- */
655
- static LoadInstance(url, elementId) {
656
- Unity.#instanceReady = false;
657
- const r = new XMLHttpRequest();
658
- r.open("GET", url + "/index.html", true);
659
- r.onreadystatechange = function () {
660
- if (r.readyState !== 4 || r.status !== 200) return;
661
- document.querySelector(`#${elementId}`).innerHTML = r.responseText;
662
-
663
- const link = document.createElement('link');
664
-
665
- link.rel = 'stylesheet';
666
- link.type = 'text/css';
667
- link.href = url + "/TemplateData/style.css";
668
- document.head.appendChild(link);
669
-
670
- const indexScript = document.createElement("script");
671
- indexScript.src = url + "/index.js";
672
- document.body.appendChild(indexScript);
673
- };
674
- r.send();
675
- }
676
-
677
- /**
678
- * Gets the current Unity version.
679
- * @returns {string}
680
- */
681
- static GetVersion() {
682
- return Unity.InvokeEvent("InstanceEvent:GetUnityVersion");
683
- }
684
-
685
- /**
686
- * Gets the current build version.
687
- * @returns {string}
688
- */
689
- static GetBuildVersion() {
690
- return Unity.InvokeEvent("InstanceEvent:GetBuildVersion");
691
- }
692
-
693
- /**
694
- * Invokes a global event that can be listened to by both Unity and JS.
695
- * An optional payload can be sent, and the event can also return anything.
696
- * @param {string} eventName
697
- * @param {any} payload
698
- * @returns {any}
699
- */
700
- static InvokeEvent(eventName, payload = undefined) {
701
- const responseJson = Unity.#invokeEventInternal(eventName, payload);
702
- try {
703
- const response = JSON.parse(responseJson);
704
- if(response.hasOwnProperty("promiseId")){
705
- console.warn(`Event '${eventName}' returned a promise. Consider using InvokeEventAsync instead.`);
706
- Unity.onEvent(`PromiseResolvedEvent:${response.promiseId}`, payload => {
707
- delete Unity.#onEventListeners[`PromiseResolvedEvent:${response.promiseId}`];
708
- });
709
- }
710
- return response;
711
- }
712
- catch {
713
- return responseJson;
714
- }
715
- }
716
-
717
- /**
718
- * Async version of InvokeEvent. Invokes a global async event that can be listened to by both Unity and JS.
719
- * An optional payload can be sent, and the event can also return anything.
720
- * @param {string} eventName
721
- * @param {any} payload
722
- * @returns {Promise<any>}
723
- */
724
- static async InvokeEventAsync(eventName, payload = undefined) {
725
- return new Promise(resolve => {
726
- const responseJson = Unity.#invokeEventInternal(eventName, payload);
727
- try {
728
- const response = JSON.parse(responseJson);
729
- if(response.hasOwnProperty("promiseId")){
730
- Unity.onEvent(`PromiseResolvedEvent:${response.promiseId}`, payload => {
731
- resolve(payload);
732
- delete Unity.#onEventListeners[`PromiseResolvedEvent:${response.promiseId}`];
733
- });
734
- }
735
- else {
736
- resolve(response);
737
- }
738
- } catch {
739
- resolve(responseJson);
740
- }
741
- })
742
- }
743
-
744
- /**
745
- * Awaits the Unity WaitForEndOfFrame coroutine.
746
- * @returns {Promise<void>}
747
- */
748
- static async WaitForEndOfFrameAsync() {
749
- return new Promise((resolve) => {
750
- const eventId = crypto.randomUUID().toString();
751
- const eventName = `EndOfFrameEvent:${eventId}`;
752
-
753
- Unity.onEvent(eventName, () => {
754
- resolve();
755
- delete Unity.#onEventListeners[eventName];
756
- });
757
-
758
- Unity.InvokeEvent("InstanceEvent:WaitForEndOfFrame", eventId);
759
- });
760
- }
761
-
762
- /**
763
- * Loads a scene and awaits its completion.
764
- * @param {string} sceneName
765
- * @returns {Promise<void>}
766
- */
767
- static async LoadSceneAsync(sceneName) {
768
- return new Promise((resolve) => {
769
- const eventName = `SceneLoadedEvent:${sceneName}`;
770
- Unity.onEvent(eventName, () => {
771
- resolve();
772
- delete Unity.#onEventListeners[eventName];
773
- });
774
-
775
- Unity.InvokeEvent("InstanceEvent:LoadScene", sceneName);
776
- });
777
- }
778
-
779
- /**
780
- * Returns true if a scene is currently loading.
781
- * @returns {boolean}
782
- */
783
- static IsSceneLoading() {
784
- return Unity.InvokeEvent("InstanceEvent:IsSceneLoading");
785
- }
786
-
787
- /**
788
- * Returns the current scene load progress. If no scene is currently loading, it returns 0.
789
- * @returns {number}
790
- */
791
- static GetSceneLoadProgress() {
792
- return Unity.InvokeEvent("InstanceEvent:GetSceneLoadProgress");
793
- }
794
-
795
- /**
796
- * Loads an asset bundle from the provided URL and awaits its completion.
797
- * @param {string} bundleUrl
798
- * @returns {Promise<void>}
799
- */
800
- static async LoadBundleAsync(bundleUrl) {
801
- await Unity.InvokeEventAsync("InstanceEvent:LoadBundle", bundleUrl);
802
- }
803
-
804
- /**
805
- * This function loads the bundle, instantiates a prefab from it, and then unloads the bundle so you don't have to handle it manually.
806
- * An optional parent JS Key can be provided to place the instantiated prefab under a specific GameObject.
807
- * @param {string} bundleUrl
808
- * @param {string} prefabName
809
- * @param {string} parentKey
810
- * @returns {Promise<void>}
811
- */
812
- static async InstantiatePrefabFromBundleAsync(bundleUrl, prefabName, parentKey = "") {
813
- await Unity.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle", {
814
- bundleUrl: bundleUrl,
815
- prefabName: prefabName,
816
- parentKey: parentKey
817
- });
818
- }
819
-
820
- // Listeners -----------------------------
821
-
822
- /**
823
- * Registers a callback that will be invoked when the Unity instance is ready.
824
- * @param {function} callback
825
- */
826
- static onInstanceReady(callback) {
827
- if(!Unity.#instanceReady) {
828
- Unity.#onInstanceReadyListeners.add(callback);
829
- }
830
- else {
831
- callback();
832
- }
833
- }
834
-
835
- /**
836
- * Registers a callback that will be invoked when a global event is received. It can listen to events from both Unity and JS.
837
- * @param {string} eventName
838
- * @param {function} callback
839
- */
840
- static onEvent(eventName, callback) {
841
- if(!Unity.#onEventListeners.hasOwnProperty(eventName)) {
842
- Unity.#onEventListeners[eventName] = new Set();
843
- }
844
- Unity.#onEventListeners[eventName].add(callback);
845
- }
846
-
847
- /**
848
- * Unregisters a callback previously registered with onEvent.
849
- * @param {string} eventName
850
- * @param {function} callback
851
- */
852
- static offEvent(eventName, callback) {
853
- if(!Unity.#onEventListeners.hasOwnProperty(eventName)) return;
854
- Unity.#onEventListeners[eventName].delete(callback);
855
- }
856
-
857
- static #invokeEventInternal(eventName, payload) {
858
- if(payload === undefined || payload === null) payload = "";
859
- let payloadJson = payload;
860
- if(typeof payload === "object") payloadJson = JSON.stringify(payload);
861
- else if(typeof payload !== "string") payloadJson = payload.toString();
862
- const responseJson = Unity.#clientEventCallback(eventName, payloadJson);
863
- Unity.#onEventListeners[eventName]?.forEach(callback => callback(payloadJson));
864
- return responseJson;
865
- }
866
-
867
- // JSLib usage -----------------------------
868
-
869
- /**Only for unity js library use*/
870
- static _instanceReady() {
871
- Unity.#instanceReady = true;
872
- Unity.#onInstanceReadyListeners.forEach(callback => callback());
873
- }
874
-
875
- /**Only for unity js library use*/
876
- static _registerClientListener(callback) {
877
- Unity.#clientEventCallback = callback;
878
- }
879
-
880
- /**Only for unity js library use*/
881
- static _receiveEvent(eventName, payloadJson) {
882
- let payload = payloadJson;
883
- try {
884
- payload = JSON.parse(payloadJson);
885
- } catch {}
886
-
887
- Unity.InvokeEvent(eventName, payload);
888
- }
889
-
890
- /**Only for unity js library use*/
891
- static _logFromUnity(verbosity, message) {
892
- if(verbosity === "internal" && !Unity.internalLogs) return;
893
- if(verbosity === "error") console.error(`[Unity] ${message}`);
894
- else if(verbosity === "warning") console.warn(`[Unity] ${message}`);
895
- else console.log(`[Unity] ${message}`);
896
- }
897
-
634
+ let Unity$1 = class Unity {
635
+ /** @type {typeof GameObject} */
636
+ static GameObject = GameObject;
637
+ /** @type {typeof Time} */
638
+ static Time = Time;
639
+ static internalLogs = false;
640
+ static types = {
641
+ int: "System.Int32",
642
+ float: "System.Single",
643
+ double: "System.Double",
644
+ bool: "System.Boolean",
645
+ string: "System.String",
646
+ char: "System.Char",
647
+ byte: "System.Byte",
648
+ long: "System.Int64",
649
+ short: "System.Int16",
650
+ decimal: "System.Decimal",
651
+ object: "System.Object",
652
+ customClass: (className, namespace = "", assembly = "Assembly-CSharp") => {
653
+ const qualifiedName = namespace === "" ? className : `${namespace}.${className}`;
654
+ return `${qualifiedName}, ${assembly}.dll`;
655
+ },
656
+ };
657
+
658
+ static #clientEventCallback;
659
+ static #instanceReady = false;
660
+ static #onInstanceReadyListeners = new Set();
661
+ static #onEventListeners = {};
662
+
663
+ /**
664
+ * Loads the Unity canvas from the specified URL and injects it into the specified element.
665
+ * @param {string} url
666
+ * @param {string} elementId
667
+ */
668
+ static LoadInstance(url, elementId) {
669
+ Unity.#instanceReady = false;
670
+ const r = new XMLHttpRequest();
671
+ r.open("GET", url + "/index.html", true);
672
+ r.onreadystatechange = function () {
673
+ if (r.readyState !== 4 || r.status !== 200) return;
674
+ document.querySelector(`#${elementId}`).innerHTML = r.responseText;
675
+
676
+ const link = document.createElement('link');
677
+
678
+ link.rel = 'stylesheet';
679
+ link.type = 'text/css';
680
+ link.href = url + "/TemplateData/style.css";
681
+ document.head.appendChild(link);
682
+
683
+ const indexScript = document.createElement("script");
684
+ indexScript.src = url + "/index.js";
685
+ document.body.appendChild(indexScript);
686
+ };
687
+ r.send();
688
+ }
689
+
690
+ /**
691
+ * Gets the current Unity version.
692
+ * @returns {string}
693
+ */
694
+ static GetVersion() {
695
+ return Unity.InvokeEvent("InstanceEvent:GetUnityVersion");
696
+ }
697
+
698
+ /**
699
+ * Gets the current build version.
700
+ * @returns {string}
701
+ */
702
+ static GetBuildVersion() {
703
+ return Unity.InvokeEvent("InstanceEvent:GetBuildVersion");
704
+ }
705
+
706
+ /**
707
+ * Invokes a global event that can be listened to by both Unity and JS.
708
+ * An optional payload can be sent, and the event can also return anything.
709
+ * @param {string} eventName
710
+ * @param {any} payload
711
+ * @returns {any}
712
+ */
713
+ static InvokeEvent(eventName, payload = undefined) {
714
+ const responseJson = Unity.#invokeEventInternal(eventName, payload);
715
+ try {
716
+ const response = JSON.parse(responseJson);
717
+ if(response.hasOwnProperty("promiseId")){
718
+ console.warn(`Event '${eventName}' returned a promise. Consider using InvokeEventAsync instead.`);
719
+ Unity.onEvent(`PromiseResolvedEvent:${response.promiseId}`, payload => {
720
+ delete Unity.#onEventListeners[`PromiseResolvedEvent:${response.promiseId}`];
721
+ });
722
+ }
723
+ return response;
724
+ }
725
+ catch {
726
+ return responseJson;
727
+ }
728
+ }
729
+
730
+ /**
731
+ * Async version of InvokeEvent. Invokes a global async event that can be listened to by both Unity and JS.
732
+ * An optional payload can be sent, and the event can also return anything.
733
+ * @param {string} eventName
734
+ * @param {any} payload
735
+ * @returns {Promise<any>}
736
+ */
737
+ static async InvokeEventAsync(eventName, payload = undefined) {
738
+ return new Promise(resolve => {
739
+ const responseJson = Unity.#invokeEventInternal(eventName, payload);
740
+ try {
741
+ const response = JSON.parse(responseJson);
742
+ if(response.hasOwnProperty("promiseId")){
743
+ Unity.onEvent(`PromiseResolvedEvent:${response.promiseId}`, payload => {
744
+ resolve(payload);
745
+ delete Unity.#onEventListeners[`PromiseResolvedEvent:${response.promiseId}`];
746
+ });
747
+ }
748
+ else {
749
+ resolve(response);
750
+ }
751
+ } catch {
752
+ resolve(responseJson);
753
+ }
754
+ })
755
+ }
756
+
757
+ /**
758
+ * Awaits the Unity WaitForEndOfFrame coroutine.
759
+ * @returns {Promise<void>}
760
+ */
761
+ static async WaitForEndOfFrameAsync() {
762
+ return new Promise((resolve) => {
763
+ const eventId = crypto.randomUUID().toString();
764
+ const eventName = `EndOfFrameEvent:${eventId}`;
765
+
766
+ Unity.onEvent(eventName, () => {
767
+ resolve();
768
+ delete Unity.#onEventListeners[eventName];
769
+ });
770
+
771
+ Unity.InvokeEvent("InstanceEvent:WaitForEndOfFrame", eventId);
772
+ });
773
+ }
774
+
775
+ /**
776
+ * Loads a scene and awaits its completion.
777
+ * @param {string} sceneName
778
+ * @returns {Promise<void>}
779
+ */
780
+ static async LoadSceneAsync(sceneName) {
781
+ return new Promise((resolve) => {
782
+ const eventName = `SceneLoadedEvent:${sceneName}`;
783
+ Unity.onEvent(eventName, () => {
784
+ resolve();
785
+ delete Unity.#onEventListeners[eventName];
786
+ });
787
+
788
+ Unity.InvokeEvent("InstanceEvent:LoadScene", sceneName);
789
+ });
790
+ }
791
+
792
+ /**
793
+ * Returns true if a scene is currently loading.
794
+ * @returns {boolean}
795
+ */
796
+ static IsSceneLoading() {
797
+ return Unity.InvokeEvent("InstanceEvent:IsSceneLoading");
798
+ }
799
+
800
+ /**
801
+ * Returns the current scene load progress. If no scene is currently loading, it returns 0.
802
+ * @returns {number}
803
+ */
804
+ static GetSceneLoadProgress() {
805
+ return Unity.InvokeEvent("InstanceEvent:GetSceneLoadProgress");
806
+ }
807
+
808
+ /**
809
+ * Loads an asset bundle from the provided URL and awaits its completion.
810
+ * @param {string} bundleUrl
811
+ * @returns {Promise<void>}
812
+ */
813
+ static async LoadBundleAsync(bundleUrl) {
814
+ await Unity.InvokeEventAsync("InstanceEvent:LoadBundle", bundleUrl);
815
+ }
816
+
817
+ /**
818
+ * This function loads the bundle, instantiates a prefab from it, and then unloads the bundle so you don't have to handle it manually.
819
+ * An optional parent JS Key can be provided to place the instantiated prefab under a specific GameObject.
820
+ * @param {string} bundleUrl
821
+ * @param {string} prefabName
822
+ * @param {string} parentKey
823
+ * @returns {Promise<void>}
824
+ */
825
+ static async InstantiatePrefabFromBundleAsync(bundleUrl, prefabName, parentKey = "") {
826
+ await Unity.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle", {
827
+ bundleUrl: bundleUrl,
828
+ prefabName: prefabName,
829
+ parentKey: parentKey
830
+ });
831
+ }
832
+
833
+ // Listeners -----------------------------
834
+
835
+ /**
836
+ * Registers a callback that will be invoked when the Unity instance is ready.
837
+ * @param {function} callback
838
+ */
839
+ static onInstanceReady(callback) {
840
+ if(!Unity.#instanceReady) {
841
+ Unity.#onInstanceReadyListeners.add(callback);
842
+ }
843
+ else {
844
+ callback();
845
+ }
846
+ }
847
+
848
+ /**
849
+ * Registers a callback that will be invoked when a global event is received. It can listen to events from both Unity and JS.
850
+ * @param {string} eventName
851
+ * @param {function} callback
852
+ */
853
+ static onEvent(eventName, callback) {
854
+ if(!Unity.#onEventListeners.hasOwnProperty(eventName)) {
855
+ Unity.#onEventListeners[eventName] = new Set();
856
+ }
857
+ Unity.#onEventListeners[eventName].add(callback);
858
+ }
859
+
860
+ /**
861
+ * Unregisters a callback previously registered with onEvent.
862
+ * @param {string} eventName
863
+ * @param {function} callback
864
+ */
865
+ static offEvent(eventName, callback) {
866
+ if(!Unity.#onEventListeners.hasOwnProperty(eventName)) return;
867
+ Unity.#onEventListeners[eventName].delete(callback);
868
+ }
869
+
870
+ static #invokeEventInternal(eventName, payload) {
871
+ if(payload === undefined || payload === null) payload = "";
872
+ let payloadJson = payload;
873
+ if(typeof payload === "object") payloadJson = JSON.stringify(payload);
874
+ else if(typeof payload !== "string") payloadJson = payload.toString();
875
+ const responseJson = Unity.#clientEventCallback(eventName, payloadJson);
876
+ Unity.#onEventListeners[eventName]?.forEach(callback => callback(payloadJson));
877
+ return responseJson;
878
+ }
879
+
880
+ // JSLib usage -----------------------------
881
+
882
+ /**Only for unity js library use*/
883
+ static _instanceReady() {
884
+ Unity.#instanceReady = true;
885
+ Unity.#onInstanceReadyListeners.forEach(callback => callback());
886
+ }
887
+
888
+ /**Only for unity js library use*/
889
+ static _registerClientListener(callback) {
890
+ Unity.#clientEventCallback = callback;
891
+ }
892
+
893
+ /**Only for unity js library use*/
894
+ static _receiveEvent(eventName, payloadJson) {
895
+ let payload = payloadJson;
896
+ try {
897
+ payload = JSON.parse(payloadJson);
898
+ } catch {}
899
+
900
+ Unity.InvokeEvent(eventName, payload);
901
+ }
902
+
903
+ /**Only for unity js library use*/
904
+ static _logFromUnity(verbosity, message) {
905
+ if(verbosity === "internal" && !Unity.internalLogs) return;
906
+ if(verbosity === "error") console.error(`[Unity] ${message}`);
907
+ else if(verbosity === "warning") console.warn(`[Unity] ${message}`);
908
+ else console.log(`[Unity] ${message}`);
909
+ }
910
+
898
911
  };
899
912
 
900
913
  return Unity$1;