Unity - Standalone .EXE file accessing from local file manager

24 views Asked by At
 'using UnityEngine;
        using UnityEngine.UI;
    using System.Collections;
    using System.IO;
          using UnityEngine.Networking;

    public class OpenFile : MonoBehaviour
{
    private string path;
    public Image image;
    public ImageContainer imageContainer; // Reference to your ScriptableObject

    // Specify the folder path for saved sprites
    private string savedSpritesFolder = "Assets/loadingImag/";

    public void OpenExplorer()
    {
    #if UNITY_WEBGL
        // Call a JavaScript function to trigger file selection
        CallJSOpenFileDialog();
#else
        path = UnityEditor.EditorUtility.OpenFilePanel("Overwrite With Png", "", "png");
        GetImage();
#endif
    }

    private void CallJSOpenFileDialog()
    {
        // Call a JavaScript function to open file dialog
        Application.ExternalEval("OpenFileDialog()");
    }

    // JavaScript function to handle file selection
    public void OnFileSelected(string filePath)
    {
        path = filePath;
        GetImage();
    }

    private void Awake()
    {
        string folderPath = Application.dataPath + "/loadingImag/";

        if (Directory.Exists(folderPath))
        {
            string[] files = Directory.GetFiles(folderPath);

            foreach (string file in files)
            {
                if (File.Exists(file))
                {
                    File.Delete(file);
                    Debug.Log("Deleted: " + file);
                }
            }

            Debug.Log("All files in loadingImag folder have been deleted.");
        }
        else
        {
            Debug.LogWarning("The loadingImag folder does not exist.");
        }
    }

    private void GetImage()
    {
        if (!string.IsNullOrEmpty(path))
        {
            StartCoroutine(UpdateImage());
        }
    }

         private IEnumerator UpdateImage()
    {
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture("file:///" + path))
        {
            yield return www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.ConnectionError || www.result ==  UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError("Failed to load image: " + www.error);
            }
            else
            {
                Texture2D texture = DownloadHandlerTexture.GetContent(www);

                // Create a sprite from the texture
                Sprite sprite = ConvertTextureToSprite(texture);

                // Assign the sprite to the Image component
                image.sprite = sprite;

                // Save changes to the ImageContainer asset
    #if UNITY_EDITOR
                UnityEditor.EditorUtility.SetDirty(imageContainer);
                UnityEditor.AssetDatabase.SaveAssets();
                UnityEditor.AssetDatabase.Refresh();
#endif

                // Save the sprite as an asset in the specified folder
                ImportTextureAsSprite(texture, savedSpritesFolder +      Path.GetFileNameWithoutExtension(path) + ".png");
             }
        }
    }

    Sprite ConvertTextureToSprite(Texture2D texture)
    {
        // Create a sprite from the texture
        Rect rect = new Rect(0, 0, texture.width, texture.height);
        Sprite sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
        return sprite;
    }

    void ImportTextureAsSprite(Texture2D texture, string assetPath)
    {
        // Save the texture asset
        byte[] bytes = texture.EncodeToPNG();
        File.WriteAllBytes(assetPath, bytes);
     #if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();

        // Import the saved texture as a sprite
        UnityEditor.TextureImporter importer = UnityEditor.AssetImporter.GetAtPath(assetPath) as         UnityEditor.TextureImporter;
        importer.textureType = UnityEditor.TextureImporterType.Sprite;
        importer.spriteImportMode = UnityEditor.SpriteImportMode.Single;
        importer.spritePixelsPerUnit = 100; // Adjust as needed
        importer.alphaIsTransparency = true;
        importer.SaveAndReimport();
#endif
    }
    }`

I am seeking assistance with a Unity script designed to open the user's local file manager, enabling them to select an image. The selected image should then be displayed in an image UI element within the canvas. Additionally, I aim to import the chosen image as a texture to a sprite, placing it in a specified folder. It's crucial to note that this functionality currently operates exclusively within the Unity Editor environment. I am eager to explore solutions that extend this capability to standalone EXE builds or WebGL deployments. Any insights or guidance on adapting the script for these contexts would be greatly appreciated.

I've successfully implemented a Unity script that opens the local file manager, allowing users to select an image. The selected image is then displayed in an image UI element within the canvas, and the script imports the image as a texture to a sprite, placing it in a designated folder. However, it's important to note that this functionality is currently limited to the Unity Editor.

Now, I'm exploring options to make this script work seamlessly in standalone EXE builds or WebGL deployments. I've attempted a few approaches, but none have yielded the desired results so far. I'm seeking guidance or suggestions on how to adapt the script for these environments, ensuring the same user-friendly image selection and display functionality.

0

There are 0 answers