// Assets/Scripts/FileUploader.cs using System; using System.Runtime.InteropServices; using UnityEngine; // Helper component to get a file public class FileUploader : MonoBehaviour { private void Start() { // We don't need to delete it on the new scene, because system is singletone DontDestroyOnLoad(gameObject); } // This method is called from JS via SendMessage void FileRequestCallback(string path) { // Sending the received link back to the FileUploaderHelper //FileUploaderHelper.SetResult(path); } } public static class FileUploaderHelper { static FileUploader fileUploaderObject; static Action pathCallback; static FileUploaderHelper() { string methodName = "FileRequestCallback"; // We will not use reflection, so as not to complicate things, hardcode :) string objectName = typeof(FileUploaderHelper).Name; // But not here // Create a helper object for the FileUploader system var wrapperGameObject = new GameObject(objectName, typeof(FileUploader)); fileUploaderObject = wrapperGameObject.GetComponent(); // Initializing the JS part of the FileUploader system /// InitFileLoader(objectName, methodName); } /// /// Requests a file from the user. /// Should be called when the user clicks! /// /// Will be called after the user selects a file, the Http path to the file is passed as a parameter /// File extensions that can be selected, example: ".jpg, .jpeg, .png" public static void RequestFileUploader(Action callback, string extensions = ".jpg, .jpeg, .png") { //RequestUserFileUploader(extensions); pathCallback = callback; } /// /// For internal use /// /// The path to the file public static void SetResult(string path) { pathCallback.Invoke(path); Dispose(); } private static void Dispose() { //ResetFileLoader(); pathCallback = null; } // Below we declare external functions from our .jslib file // [DllImport("__Internal")] // private static extern void InitFileLoader(string objectName, string methodName); // [DllImport("__Internal")] // private static extern void RequestUserFileUploader(string extensions); // [DllImport("__Internal")] // private static extern void ResetFileLoader(); }