@pizzapopcorn/unijs 0.0.5 → 0.0.6

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,12 +4,305 @@
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
+ }
152
+ }
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
+ }
295
+ }
296
+
7
297
  class GameObject {
298
+ #transform = null;
299
+ #rigidbody = null;
8
300
 
9
301
  static keyGameObjects = {};
10
302
  static #lifeCycleCallbacks = {
11
303
  awake: {},
12
304
  start: {},
305
+ update: {},
13
306
  enable: {},
14
307
  disable: {},
15
308
  destroy: {}
@@ -28,6 +321,24 @@
28
321
  }
29
322
  return GameObject.keyGameObjects[key];
30
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
+ }
31
342
 
32
343
  /**
33
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.
@@ -52,6 +363,18 @@
52
363
  }
53
364
  GameObject.#lifeCycleCallbacks.start[key].add(callback);
54
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
+ }
55
378
 
56
379
  /**
57
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.
@@ -89,10 +412,12 @@
89
412
  GameObject.#lifeCycleCallbacks.destroy[key].add(callback);
90
413
  }
91
414
 
415
+ /**Only for unity js library use*/
92
416
  static _register(key, data) {
93
417
  GameObject.keyGameObjects[key] = new GameObject(key, data);
94
418
  }
95
419
 
420
+ /**Only for unity js library use*/
96
421
  static _receiveLifeCycleEvent(key, event) {
97
422
  const gameObject = GameObject.keyGameObjects[key];
98
423
  if(!gameObject) return;
@@ -104,7 +429,6 @@
104
429
  }
105
430
  }
106
431
  if(event === "destroy") {
107
- gameObject.transform = null;
108
432
  delete GameObject.keyGameObjects[key];
109
433
  }
110
434
  }
@@ -112,16 +436,39 @@
112
436
  constructor(key, data) {
113
437
  this.key = key;
114
438
  this.name = data.name;
115
- this.transform = data.transform;
439
+ this.#transform = new Transform(this);
440
+ if(data.hasRigidbody) {
441
+ this.#rigidbody = new Rigidbody(this);
442
+ }
116
443
  this.hierarchyPath = data.hasOwnProperty("hierarchyPath") ? data.hierarchyPath : "";
117
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
+ }
118
465
 
119
466
  /**
120
467
  * Sets the GameObject's active state.
121
468
  * @param {boolean} active
122
469
  */
123
470
  SetActive(active) {
124
- this?.#invokeGameObjectEvent("gameObject.setActive", active);
471
+ this?._invokeGameObjectEvent("gameObject.setActive", active);
125
472
  }
126
473
 
127
474
  /**
@@ -133,7 +480,7 @@
133
480
  */
134
481
  InvokeMethod(methodName, paramType = "", paramValue = "") {
135
482
  paramType = Unity.types[paramType] || paramType;
136
- this?.#invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
483
+ this?._invokeGameObjectEvent("gameObject.invokeMethod", { methodName: methodName, parameterType: paramType, parameterValue: paramValue });
137
484
  }
138
485
 
139
486
  /**
@@ -143,7 +490,7 @@
143
490
  */
144
491
  GetChild(query) {
145
492
  const eventName = typeof query === "string" ? "gameObject.findChild" : "gameObject.getChild";
146
- const childData = this?.#invokeGameObjectEvent(eventName, query);
493
+ const childData = this?._invokeGameObjectEvent(eventName, query);
147
494
  if(childData !== null) {
148
495
  const currentPath = this.hierarchyPath === "" ? this.key : this.hierarchyPath;
149
496
  childData.hierarchyPath = currentPath + "/" + childData.name;
@@ -152,64 +499,45 @@
152
499
  return null;
153
500
  }
154
501
 
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
- */
161
- Translate(x, y, z) {
162
- this?.#invokeGameObjectEvent("transform.translate", { x: x, y: y, z: z });
163
- }
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
- */
171
- Rotate(x, y, z) {
172
- this?.#invokeGameObjectEvent("transform.rotate", { x: x, y: y, z: z });
173
- }
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
- */
181
- SetLocalScale(x, y, z) {
182
- this?.#invokeGameObjectEvent("transform.setLocalScale", { x: x, y: y, z: z });
183
- }
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
- */
191
- SetLocalPosition(x, y, z) {
192
- this?.#invokeGameObjectEvent("transform.setLocalPosition", { x: x, y: y, z: z });
193
- }
194
-
195
502
  /**
196
503
  * Looks for a text component and sets its text to the specified value. It works with Legacy, TextMeshPro, and TextMesh components.
197
504
  * @param {string} text
198
505
  */
199
506
  SetText(text) {
200
- this?.#invokeGameObjectEvent("text.setText", text);
507
+ this?._invokeGameObjectEvent("text.setText", text);
201
508
  }
202
509
 
203
510
  /**
204
511
  * Destroys the GameObject.
205
512
  */
206
513
  Destroy() {
207
- this?.#invokeGameObjectEvent("gameObject.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);
208
537
  }
209
538
 
210
- #invokeGameObjectEvent(eventName, payload) {
211
- if(!this.transform) return null;
212
-
539
+ /**Only for internal library use*/
540
+ _invokeGameObjectEvent(eventName, payload) {
213
541
  let payloadJson = payload;
214
542
  if(typeof payload === "object") payloadJson = JSON.stringify(payload);
215
543
  else if(typeof payload !== "string") payloadJson = payload.toString();
@@ -236,9 +564,65 @@
236
564
  }
237
565
  }
238
566
 
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
+ }
619
+ }
620
+
239
621
  let Unity$1 = class Unity {
240
622
  /** @type {typeof GameObject} */
241
623
  static GameObject = GameObject;
624
+ /** @type {typeof Time} */
625
+ static Time = Time;
242
626
  static internalLogs = false;
243
627
  static types = {
244
628
  int: "System.Int32",
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 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}`))}}});
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{constructor(e){this.gameObject=e}get position(){return this.#e("transform.getPosition","")}set position(e){this.#t(e),this.#e("transform.setPosition",e)}get localPosition(){return this.#e("transform.getLocalPosition","")}set localPosition(e){this.#t(e),this.#e("transform.setLocalPosition",e)}get rotation(){return this.#e("transform.getRotation","")}set rotation(e){this.#n(e),this.#e("transform.setRotation",e)}get eulerAngles(){return this.#e("transform.getEulerAngles","")}set eulerAngles(e){console.warn("[Unity] eulerAngles is read-only.")}get localScale(){return this.#e("transform.getLocalScale","")}set localScale(e){this.#t(e),this.#e("transform.setLocalScale",e)}get lossyScale(){return this.#e("transform.getLossyScale","")}set lossyScale(e){console.warn("[Unity] lossyScale is read-only.")}Translate(e,t,n){this.#e("transform.translate",{x:e,y:t,z:n})}Rotate(e,t,n){this.#e("transform.rotate",{x:e,y:t,z:n})}#e(e,t){return this.gameObject||console.error("[Unity] The GameObject associated with this Transform is null"),this.gameObject._invokeGameObjectEvent(e,t)}#t(e){if("object"!=typeof e||null===e||"number"!=typeof e.x||"number"!=typeof e.y||"number"!=typeof e.z)throw new Error(`[Unity] Invalid Vector3: ${JSON.stringify(e)}`)}#n(e){if("object"!=typeof e||null===e||"number"!=typeof e.x||"number"!=typeof e.y||"number"!=typeof e.z||"number"!=typeof e.w)throw new Error(`[Unity] Invalid Quaternion: ${JSON.stringify(e)}`)}}class t{constructor(e){this.gameObject=e}get mass(){return this.#e("physics.getMass","")}get useGravity(){return this.#e("physics.getUseGravity","")}get isKinematic(){return this.#e("physics.getIsKinematic","")}get linearDamping(){return this.#e("physics.getLinearDamping","")}get angularDamping(){return this.#e("physics.getAngularDamping","")}AddForce(e,t,n){this.#e("physics.addForce",{x:e,y:t,z:n})}AddTorque(e,t,n){this.#e("physics.addTorque",{x:e,y:t,z:n})}SetVelocity(e,t,n){this.#e("physics.setVelocity",{x:e,y:t,z:n})}GetVelocity(){return this.#e("physics.getVelocity","")}SetAngularVelocity(e,t,n){this.#e("physics.setAngularVelocity",{x:e,y:t,z:n})}GetAngularVelocity(){return this.#e("physics.getAngularVelocity","")}SetUseGravity(e){this.#e("physics.setUseGravity",e)}SetIsKinematic(e){this.#e("physics.setIsKinematic",e)}SetMass(e){this.#e("physics.setMass",e)}SetLinearDamping(e){this.#e("physics.setLinearDamping",e)}#e(e,t){return this.gameObject?this.gameObject._invokeGameObjectEvent(e,t):(console.error("[Unity] The GameObject associated with this RigidBody is null"),null)}}class n{#s=null;#a=null;static keyGameObjects={};static#i={awake:{},start:{},update:{},enable:{},disable:{},destroy:{}};static GetKeyGameObject(e){return n.keyGameObjects.hasOwnProperty(e)?n.keyGameObjects[e]:(console.error(`GameObject with key '${e}' not found`),null)}static Instantiate(t,s={x:0,y:0,z:0},a={x:0,y:0,z:0,w:1},i=null){if(null===i)Unity.InvokeEvent("InstanceEvent:InstantiateGameObject",{prefabPath:t,position:s,rotation:a});else{const r=i instanceof n?i:i instanceof e?i.gameObject:null;if(null===r)return;r.Instantiate(t,s,a)}}static onAwake(e,t){n.#i.awake.hasOwnProperty(e)||(n.#i.awake[e]=new Set),n.#i.awake[e].add(t)}static onStart(e,t){n.#i.start.hasOwnProperty(e)||(n.#i.start[e]=new Set),n.#i.start[e].add(t)}static onUpdate(e,t){n.#i.update.hasOwnProperty(e)||(n.#i.update[e]=new Set),n.#i.update[e].add(t)}static onEnable(e,t){n.#i.enable.hasOwnProperty(e)||(n.#i.enable[e]=new Set),n.#i.enable[e].add(t)}static onDisable(e,t){n.#i.disable.hasOwnProperty(e)||(n.#i.disable[e]=new Set),n.#i.disable[e].add(t)}static onDestroy(e,t){n.#i.destroy.hasOwnProperty(e)||(n.#i.destroy[e]=new Set),n.#i.destroy[e].add(t)}static _register(e,t){n.keyGameObjects[e]=new n(e,t)}static _receiveLifeCycleEvent(e,t){const s=n.keyGameObjects[e];if(!s)return;const a=n.#i[t][e];if(a)for(const e of a)e(s);"destroy"===t&&delete n.keyGameObjects[e]}constructor(n,s){this.key=n,this.name=s.name,this.#s=new e(this),s.hasRigidbody&&(this.#a=new t(this)),this.hierarchyPath=s.hasOwnProperty("hierarchyPath")?s.hierarchyPath:""}get transform(){return this.#s}get rigidbody(){return this.HasComponent("Rigidbody")?(this.#a=new t(this),this.#a):null}SetActive(e){this?._invokeGameObjectEvent("gameObject.setActive",e)}InvokeMethod(e,t="",n=""){t=Unity.types[t]||t,this?._invokeGameObjectEvent("gameObject.invokeMethod",{methodName:e,parameterType:t,parameterValue:n})}GetChild(e){const t="string"==typeof e?"gameObject.findChild":"gameObject.getChild",s=this?._invokeGameObjectEvent(t,e);if(null!==s){const e=""===this.hierarchyPath?this.key:this.hierarchyPath;return s.hierarchyPath=e+"/"+s.name,new n(this.key,s)}return null}SetText(e){this?._invokeGameObjectEvent("text.setText",e)}Destroy(){this?._invokeGameObjectEvent("gameObject.destroy","")}Instantiate(e,t={x:0,y:0,z:0},n={x:0,y:0,z:0,w:1}){this?._invokeGameObjectEvent("gameObject.instantiate",{prefabPath:e,position:t,rotation:n})}HasComponent(e){return this?._invokeGameObjectEvent("gameObject.hasComponent",e)}GetComponent(e){return this?._invokeGameObjectEvent("gameObject.getComponent",e)}AddComponent(e){return this?._invokeGameObjectEvent("gameObject.addComponent",e)}_invokeGameObjectEvent(e,t){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}}class s{static get time(){return Unity.InvokeEvent("InstanceEvent:GetTime")}static get deltaTime(){return Unity.InvokeEvent("InstanceEvent:GetDeltaTime")}static get fixedDeltaTime(){return Unity.InvokeEvent("InstanceEvent:GetFixedDeltaTime")}static get unscaledDeltaTime(){return Unity.InvokeEvent("InstanceEvent:GetUnscaledDeltaTime")}static get realtimeSinceStartup(){return Unity.InvokeEvent("InstanceEvent:GetRealtimeSinceStartup")}static get timeScale(){return Unity.InvokeEvent("InstanceEvent:GetTimeScale")}static set timeScale(e){Unity.InvokeEvent("InstanceEvent:SetTimeScale",e)}}return class e{static GameObject=n;static Time=s;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#r;static#o=!1;static#c=new Set;static#l={};static LoadInstance(t,n){e.#o=!1;const s=new XMLHttpRequest;s.open("GET",t+"/index.html",!0),s.onreadystatechange=function(){if(4!==s.readyState||200!==s.status)return;document.querySelector(`#${n}`).innerHTML=s.responseText;const e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t+"/TemplateData/style.css",document.head.appendChild(e);const a=document.createElement("script");a.src=t+"/index.js",document.body.appendChild(a)},s.send()}static GetVersion(){return e.InvokeEvent("InstanceEvent:GetUnityVersion")}static GetBuildVersion(){return e.InvokeEvent("InstanceEvent:GetBuildVersion")}static InvokeEvent(t,n=void 0){const s=e.#y(t,n);try{const n=JSON.parse(s);return n.hasOwnProperty("promiseId")&&(console.warn(`Event '${t}' returned a promise. Consider using InvokeEventAsync instead.`),e.onEvent(`PromiseResolvedEvent:${n.promiseId}`,t=>{delete e.#l[`PromiseResolvedEvent:${n.promiseId}`]})),n}catch{return s}}static async InvokeEventAsync(t,n=void 0){return new Promise(s=>{const a=e.#y(t,n);try{const t=JSON.parse(a);t.hasOwnProperty("promiseId")?e.onEvent(`PromiseResolvedEvent:${t.promiseId}`,n=>{s(n),delete e.#l[`PromiseResolvedEvent:${t.promiseId}`]}):s(t)}catch{s(a)}})}static async WaitForEndOfFrameAsync(){return new Promise(t=>{const n=crypto.randomUUID().toString(),s=`EndOfFrameEvent:${n}`;e.onEvent(s,()=>{t(),delete e.#l[s]}),e.InvokeEvent("InstanceEvent:WaitForEndOfFrame",n)})}static async LoadSceneAsync(t){return new Promise(n=>{const s=`SceneLoadedEvent:${t}`;e.onEvent(s,()=>{n(),delete e.#l[s]}),e.InvokeEvent("InstanceEvent:LoadScene",t)})}static IsSceneLoading(){return e.InvokeEvent("InstanceEvent:IsSceneLoading")}static GetSceneLoadProgress(){return e.InvokeEvent("InstanceEvent:GetSceneLoadProgress")}static async LoadBundleAsync(t){await e.InvokeEventAsync("InstanceEvent:LoadBundle",t)}static async InstantiatePrefabFromBundleAsync(t,n,s=""){await e.InvokeEventAsync("InstanceEvent:InstantiatePrefabFromBundle",{bundleUrl:t,prefabName:n,parentKey:s})}static onInstanceReady(t){e.#o?t():e.#c.add(t)}static onEvent(t,n){e.#l.hasOwnProperty(t)||(e.#l[t]=new Set),e.#l[t].add(n)}static offEvent(t,n){e.#l.hasOwnProperty(t)&&e.#l[t].delete(n)}static#y(t,n){null==n&&(n="");let s=n;"object"==typeof n?s=JSON.stringify(n):"string"!=typeof n&&(s=n.toString());const a=e.#r(t,s);return e.#l[t]?.forEach(e=>e(s)),a}static _instanceReady(){e.#o=!0,e.#c.forEach(e=>e())}static _registerClientListener(t){e.#r=t}static _receiveEvent(t,n){let s=n;try{s=JSON.parse(n)}catch{}e.InvokeEvent(t,s)}static _logFromUnity(t,n){("internal"!==t||e.internalLogs)&&("error"===t?console.error(`[Unity] ${n}`):"warning"===t?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.5",
3
+ "version": "0.0.6",
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": [