open a file
#if UNITY_WEBGL && !UNITY_EDITOR
//
// WebGL
//
[DllImport("__Internal")]
private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
public void OnPointerDown(PointerEventData eventData) {
UploadFile(gameObject.name, "OnFileUpload", ".png, .jpg", false);//打开图片
//UploadFile(gameObject.name, "OnFileUpload", ".txt", false);打开文本
}
// Called from browser
public void OnFileUpload(string url) {
StartCoroutine(OutputRoutine(url));
}
#else
void Start() {
var button = GetComponent<Button>();
button.onClick.AddListener(OnClick);
}
private void OnClick() {
var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", ".png", false);//打开 图片
//var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", "txt", false);打开文本
if (paths.Length > 0) {
StartCoroutine(OutputRoutine(new System.Uri(paths[0]).AbsoluteUri));
}
}
private IEnumerator OutputRoutine(string url) {
var loader = new WWW(url);
yield return loader;
output.texture = loader.texture;
}
download file
private byte[] _textureBytes;
//private string _data = "Example text created by StandaloneFileBrowser";
void Awake() {
// Create red texture
var width = 100;
var height = 100;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
tex.SetPixel(i, j, Color.red);
}
}
tex.Apply();
_textureBytes = tex.EncodeToPNG();
UnityEngine.Object.Destroy(tex);
}
#if UNITY_WEBGL && !UNITY_EDITOR
//
// WebGL
//
[DllImport("__Internal")]
private static extern void DownloadFile(string gameObjectName, string methodName, string filename, byte[] byteArray, int byteArraySize);
// Broser plugin should be called in OnPointerDown.
public void OnPointerDown(PointerEventData eventData) {
DownloadFile(gameObject.name, "OnFileDownload", "sample.png", _textureBytes, _textureBytes.Length);//下载图片
//var bytes = Encoding.UTF8.GetBytes(_data);
//DownloadFile(gameObject.name, "OnFileDownload", "sample.txt", bytes, bytes.Length);//下载文本
}
// Called from browser
public void OnFileDownload() {
output.text = "File Successfully Downloaded";
}
#else
public void OnClick() {
var path = StandaloneFileBrowser.SaveFilePanel("Title", "", "sample", "png");//图片保存
//var path = StandaloneFileBrowser.SaveFilePanel("Title", "", "sample", "txt");文本保存
if (!string.IsNullOrEmpty(path)) {
File.WriteAllBytes(path, _textureBytes);
//File.WriteAllText(path, _data);
}
}
Plugin download
https://download.csdn.net/download/qq_39556084/86264750