哇。Yuri Nudelman 的解决方案令人印象深刻,它仍然是最好的解决方案。但是: WWW-class 和 ExternalEval 现在都已弃用。
它确实会运行(带有警告),但会在不久的将来停止工作。
因此,为了帮助任何想要实现这一点的人:
两个 Javascript 函数都必须放在“插件”文件夹内的 .jslib 中。第一个是这样的:
mergeInto(
LibraryManager.library,
{
AddClickListenerForFileDialog: function () {
document.addEventListener('click', function () {
var fileuploader = document.getElementById('fileuploader');
if (!fileuploader) {
fileuploader = document.createElement('input');
fileuploader.setAttribute('style', 'display:none;');
fileuploader.setAttribute('type', 'file');
fileuploader.setAttribute('id', 'fileuploader');
fileuploader.setAttribute('class', '');
document.getElementsByTagName('body')[0].appendChild(fileuploader);
fileuploader.onchange = function (e) {
var files = e.target.files;
for (var i = 0, f; f = files[i]; i++) {
window.alert(URL.createObjectURL(f));
SendMessage('BrowserFileLoading', 'FileDialogResult', URL.createObjectURL(f));
}
};
}
if (fileuploader.getAttribute('class') == 'focused') {
fileuploader.setAttribute('class', '');
fileuploader.click();
}
});
}
}
);
请注意,我添加了两个更改:a)我删除了“专注”。这可以防止脚本在程序开始时触发:
fileuploader.setAttribute('class', '');
b) 我手动添加了 Unity GameObject 的名称。这必须与您放置(统一)脚本的游戏对象相同:
SendMessage('BrowserFileLoading', 'FileDialogResult', URL.createObjectURL(f));
您可以使用以下方法调用此外部函数:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using UnityEngine.Networking;
using System.Runtime.InteropServices;
public class BrowserFileLoadingDialog : MonoBehaviour
{
[DllImport("__Internal")] private static extern void AddClickListenerForFileDialog();
void Start()
{
AddClickListenerForFileDialog();
}
public void FileDialogResult(string fileUrl)
{
Debug.Log(fileUrl);
UrlTextField.text = fileUrl;
StartCoroutine(LoadBlob(fileUrl));
}
IEnumerator LoadBlob(string url)
{
UnityWebRequest webRequest = UnityWebRequest.Get(url);
yield return webRequest.SendWebRequest();
if (!webRequest.isNetworkError && !webRequest.isHttpError)
{
// Get text content like this:
Debug.Log(webRequest.downloadHandler.text);
}
}
第二个脚本(可以放在同一个 .jslib 文件中)如下所示:
mergeInto(
LibraryManager.library,
{
FocusFileUploader: function () {
var fileuploader = document.getElementById('fileuploader');
if (fileuploader) {
fileuploader.setAttribute('class', 'focused');
}
}
}
);
这里没有大的变化,像上面那样使用并且应该(就像 Yuri Nudelman 建议的那样)在 CursorDown 上调用。