mergeInto(LibraryManager.library, { DownloadTexture: function (dataPtr, dataLength, fileName) { var data = HEAPU8.subarray(dataPtr, dataPtr + dataLength); var fileName = UTF8ToString(fileName); var blob = new Blob([data], { type: 'image/png' }); varurl = URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }, LoadImageFile: function () { var fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = ".jpg,.png,.tga"; // 限定文件类型 fileInput.style.position = 'fixed'; // 固定定位 fileInput.style.left = '-100vw'; // 定位到屏幕外 fileInput.onchange = function (e) { varurl = URL.createObjectURL(fileInput.files[0]); window.unityInstance.Module.SendMessage('ImageLoader', 'OnImageLoaded', url); }; document.body.appendChild(fileInput); // 添加到body,使其可以被点击 fileInput.click(); // 模拟点击 setTimeout(function() { document.body.removeChild(fileInput); // 移除元素 }, 100); // 稍后移除,确保文件输入有足够的时间打开对话框 } });
文件上传
当然这里也有一些值得注意的东西:
传入的参数有类型限制
string, a number 就这俩,之前我一度尝试使用byte[],或者从js发送内存指针都提示参数类型不正确。 下面是文档摘录。 Where objectName is the name of an object in your scene; methodName is the name of a method in the script, currently attached to that object; value can be a string, a number, or can be empty. For example:
if (request.result == UnityWebRequest.Result.Success) { var imageObject = GameObject.Find("ImageObject"); var sprite = Sprite.Create(texDl.texture, new Rect(0, 0, texDl.texture.width, texDl.texture.height), new Vector2(0.5f, 0.5f)); imageObject.GetComponent<UnityEngine.UI.Image>().sprite = sprite; } else { Debug.LogError("Error downloading image: " + request.error); }
request.Dispose(); }
需要获取运行实例
下面摘录自官方文档,大致意思是js要调用unity的逻辑需要找到对应已创建的实例。
1 2 3 4
However, if you are planning to call the internal JavaScript functions from the global scope of the embedding page, you should always assume that there are multiple builds embedded on the page, so you should explicitly specify which build you are referencing to. For example, if your game has been instantiated as: var gameInstance = UnityLoader.instantiate("gameContainer", "Build/build.json", {onProgress: UnityProgress}); Then you can send a message to the build using gameInstance.SendMessage(), or access the build Module object like this gameInstance.Module.