哇。Yuri Nudelman的解决方案是令人印象深刻的黑魔法,并且仍然是目前找到的最佳解决方案。但是:现在WWW-class和ExternalEval已经被弃用。
它可以运行(有警告),但将在不久的将来停止工作。
因此,为了帮助任何想要实现这一点的人:
两个JavaScript函数必须放在“Plugins”文件夹内的.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) 我删除了“focused”。这样可以防止脚本在程序开始时触发:
fileuploader.setAttribute('class', '');
b) 我手动添加了Unity游戏对象的名称。这个名称必须与您放置(Unity)脚本的游戏对象相同:
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)
{
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事件中调用。