CanvasSampleOpenFileImage.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Text;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. using UnityEngine.EventSystems;
  8. using SFB;
  9. [RequireComponent(typeof(Button))]
  10. public class CanvasSampleOpenFileImage : MonoBehaviour, IPointerDownHandler {
  11. public RawImage output;
  12. #if UNITY_WEBGL && !UNITY_EDITOR
  13. //
  14. // WebGL
  15. //
  16. [DllImport("__Internal")]
  17. private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
  18. public void OnPointerDown(PointerEventData eventData) {
  19. UploadFile(gameObject.name, "OnFileUpload", ".png, .jpg", false);
  20. }
  21. // Called from browser
  22. public void OnFileUpload(string url) {
  23. StartCoroutine(OutputRoutine(url));
  24. }
  25. #else
  26. //
  27. // Standalone platforms & editor
  28. //
  29. public void OnPointerDown(PointerEventData eventData) { }
  30. void Start() {
  31. var button = GetComponent<Button>();
  32. button.onClick.AddListener(OnClick);
  33. }
  34. private void OnClick() {
  35. var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", ".png", false);
  36. if (paths.Length > 0) {
  37. StartCoroutine(OutputRoutine(new System.Uri(paths[0]).AbsoluteUri));
  38. }
  39. }
  40. #endif
  41. private IEnumerator OutputRoutine(string url) {
  42. var loader = new WWW(url);
  43. yield return loader;
  44. output.texture = loader.texture;
  45. }
  46. }