UNPKG

unity-webgl

Version:

Unity-WebGL provides an easy solution for embedding Unity WebGL builds in your web projects, with two-way communication between your webApp and Unity application with advanced API's.

8 lines (7 loc) 4.93 kB
/*! * unity-webgl v4.4.2 * Copyright (c) 2025 Mariner<mengqing723@gmail.com> * Released under the Apache-2.0 License. */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).UnityWebgl=e()}(this,(function(){"use strict";const t="undefined"!=typeof window&&void 0!==window.document,e=t=>"object"===(t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase())(t);const n=(()=>{const t="[unity-webgl]",e=(...e)=>console.log(t,...e);return e.warn=(...e)=>console.warn(t,...e),e.error=(...e)=>console.error(t,...e),e})();class i{constructor(){this._e={},t&&(window.dispatchUnityEvent=(t,...e)=>{t.startsWith("unity:")||(t=`unity:${t}`),this.emit.call(this,t,...e)})}on(t,e,n){if("function"!=typeof e)throw new TypeError("listener must be a function");if(this._e[t]||(this._e[t]=[]),null==n?void 0:n.once){const n=(...i)=>{this.off(t,n),e.apply(this,i)};n._=e,this._e[t].push(n)}else this._e[t].push(e);return this}off(t,e){if(e){const n=this._e[t];n&&(this._e[t]=n.filter((t=>t!==e&&t._!==e)))}else delete this._e[t];return this}emit(t,...e){return this._e[t]?(this._e[t].forEach((t=>t.apply(this,e))),this):this}clear(){this._e={}}addUnityListener(t,e,n){return t.startsWith("unity:")||(t=`unity:${t}`),this.on(t,e,n)}removeUnityListener(t,e){return t.startsWith("unity:")||(t=`unity:${t}`),this.off(t,e)}}function r(t,e){const n=function(t,e){const n=Object.assign({},t);return e.forEach((t=>{delete n[t]})),n}(e,["loaderUrl"]);return n.print=function(e){t.emit("debug",e)},n.printError=function(e){t.emit("error",e)},n}return class extends i{constructor(t,n){if(super(),this._unity=null,this._loader=null,this._canvas=null,!("string"==typeof t||t instanceof HTMLCanvasElement||e(t)))throw new TypeError("Parameter canvas is not valid");if(e(t)&&(n=t),!(n&&n.loaderUrl&&n.dataUrl&&n.frameworkUrl&&n.codeUrl))throw new TypeError("UnityConfig is not valid");this._config=n,("string"==typeof t||t instanceof HTMLCanvasElement)&&this.render(t)}create(t){return this.render(t)}render(e){return t?this._unity&&this._canvas&&this._loader?(n.warn("UnityInstance already created"),Promise.resolve()):new Promise(((n,i)=>{try{const i=function(t){return t instanceof HTMLCanvasElement?t:document.querySelector(t)}(e);if(!i)throw new Error("CanvasElement is not found");this._canvas=i;const s=this,o=r(this,this._config);this.emit("beforeMount",this),this._loader=function(e,n={}){const{resolve:i,reject:r}=n;if(!t)return null;if(!e)return r&&r(new Error(`${e} not found.`)),null;function s(t){"loaded"===t?i&&i():r&&r(new Error(`${e} loading failure.`))}let o=window.document.querySelector(`script[src="${e}"]`);if(o)s("loaded"===o.getAttribute("data-status")?"loaded":"error");else{function a(t){null==o||o.setAttribute("data-status",t),s(t)}o=window.document.createElement("script"),o.async=!0,o.setAttribute("data-status","loading"),o.addEventListener("load",(()=>a("loaded"))),o.addEventListener("error",(()=>a("error"))),o.src=e,window.document.body.appendChild(o)}return function(){o&&o.parentNode&&o.parentNode.removeChild(o)}}(this._config.loaderUrl,{resolve(){window.createUnityInstance(i,o,(t=>s.emit("progress",t))).then((t=>{s._unity=t,s.emit("mounted",s,t),n()})).catch((t=>{throw t}))},reject(t){throw t}})}catch(t){this._unity=null,this.emit("error",t),i(t)}})):Promise.resolve()}sendMessage(t,e,i){if(!this._unity)return n.warn("Unable to Send Message while Unity is not Instantiated."),this;if(null==i)this._unity.SendMessage(t,e);else{const n="object"==typeof i?JSON.stringify(i):i;this._unity.SendMessage(t,e,n)}return this}send(t,e,n){return this.sendMessage(t,e,n)}requestPointerLock(){this._unity&&this._unity.Module.canvas?this._unity.Module.canvas.requestPointerLock():n.warn("Unable to requestPointerLock while Unity is not Instantiated.")}takeScreenshot(t,e){if(this._unity&&this._unity.Module.canvas)return this._unity.Module.canvas.toDataURL(t,e);n.warn("Unable to take Screenshot while Unity is not Instantiated.")}setFullscreen(t){this._unity?this._unity.SetFullscreen(t?1:0):n.warn("Unable to set Fullscreen while Unity is not Instantiated.")}unload(){return this._unity?(this.emit("beforeUnmount",this),"function"==typeof this._loader&&(this._loader(),this._loader=null),this._unity.Quit().then((()=>{this._unity=null,this._canvas=null,this.clear(),this.emit("unmounted")})).catch((t=>{throw n.error("Unable to Unload Unity"),this.emit("error",t),t}))):(n.warn("Unable to Quit Unity while Unity is not Instantiated."),Promise.reject())}unsafe_unload(){try{if(!this._unity||!this._unity.Module.canvas)return n.warn("No UnityInstance found."),Promise.reject();const t=this._unity.Module.canvas;return document.body.appendChild(t),t.style.display="none",this.unload().then((()=>{t.remove()}))}catch(t){return Promise.reject(t)}}}})); //# sourceMappingURL=index.min.js.map