CanvasSampleSaveFileText.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.IO;
  2. using System.Text;
  3. using System.Runtime.InteropServices;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.EventSystems;
  7. using SFB;
  8. [RequireComponent(typeof(Button))]
  9. public class CanvasSampleSaveFileText : MonoBehaviour, IPointerDownHandler {
  10. public Text output;
  11. // Sample text data
  12. private string _data = "Example text created by StandaloneFileBrowser";
  13. #if UNITY_WEBGL && !UNITY_EDITOR
  14. //
  15. // WebGL
  16. //
  17. [DllImport("__Internal")]
  18. private static extern void DownloadFile(string gameObjectName, string methodName, string filename, byte[] byteArray, int byteArraySize);
  19. // Broser plugin should be called in OnPointerDown.
  20. public void OnPointerDown(PointerEventData eventData) {
  21. var bytes = Encoding.UTF8.GetBytes(_data);
  22. DownloadFile(gameObject.name, "OnFileDownload", "sample.txt", bytes, bytes.Length);
  23. }
  24. // Called from browser
  25. public void OnFileDownload() {
  26. output.text = "File Successfully Downloaded";
  27. }
  28. #else
  29. //
  30. // Standalone platforms & editor
  31. //
  32. public void OnPointerDown(PointerEventData eventData) { }
  33. // Listen OnClick event in standlone builds
  34. void Start() {
  35. var button = GetComponent<Button>();
  36. button.onClick.AddListener(OnClick);
  37. }
  38. public void OnClick() {
  39. var path = StandaloneFileBrowser.SaveFilePanel("Title", "", "sample", "txt");
  40. if (!string.IsNullOrEmpty(path)) {
  41. File.WriteAllText(path, _data);
  42. }
  43. }
  44. #endif
  45. }