Загрузка текстуры во время выполнения в Windows и Mac

#c# #windows #macos #unity3d #textures

Вопрос:

В настоящее время я изменяю некоторые текстуры во время выполнения для iOS и Android с помощью ресурса NativeGallery. Актив в основном открывает проводник файлов, позволяет выбрать файл изображения из галереи вашего телефона и загрузить его в приложение.

Поэтому используемый код является:

 public class DisplayHandler : MonoBehaviour
{
    public GameObject Display;

    public void PickImage(int maxSize)
    {
        NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
        {
            Debug.Log("Image path: "   path);
            if (path != null)
            {
                // Create Texture from selected image
                Texture2D texture = NativeGallery.LoadImageAtPath(path, maxSize);
                if (texture == null)
                {
                    Debug.Log("Couldn't load texture from "   path);
                    return;
                }

                Material material = Display.GetComponent<Renderer>().material;
                if (!material.shader.isSupported) // happens when Standard shader is not included in the build
                    material.shader = Shader.Find("Legacy Shaders/Diffuse");

                material.mainTexture = texture;

                // If a procedural texture is not destroyed manually, 
                // it will only be freed after a scene change
                //Destroy(texture, 5f);
            }
        }); // , "Wählen Sie ein Bild aus", mime: "image/*" );

        Debug.Log("Permission result: "   permission);
    }
}
 

Возможно ли получить одинаковое поведение для Windows и Mac? Так, например, нажатие кнопки открывает окно проводника/поиска, в котором вы можете выбрать файл изображения. Эквивалентом HTML будет

 #if UNITY_EDITOR_WIN
        public void ShowExplorer(string itemPath)
        {
            itemPath = itemPath.Replace(@"/", @"");   // explorer doesn't like front slashes
            System.Diagnostics.Process.Start("explorer.exe", "/select,"   itemPath);
        }
#endif

#if UNITY_EDITOR_OSX
    public void ShowExplorer(string itemPath) {
         var path = Path.Combine(Application.dataPath, "Resources");
         var file = Directory.EnumerateFiles(path).FirstOrDefault();
         if (!string.IsNullOrEmpty(file))
             EditorUtility.RevealInFinder(Path.Combine(path, file));
         else
             EditorUtility.RevealInFinder(path);
         }
#endif
 

который открывает окно проводника в Windows и Finder на Mac, но как отдельное окно, а не как диалоговое окно для выбора текстур.

Комментарии:

1. Ни один из вопросов, по-видимому, не связан с текстурами или загрузкой файлов. Решение проблем обычно начинается с выявления проблемы. Здесь такого не случалось.

2. Спасибо вам за ваши отзывы. Я добавил дополнительную информацию, чтобы, надеюсь, лучше изолировать проблему и прояснить то, что я уже пытался сделать.

3. github.com/gkngkc/UnityStandaloneFileBrowser или assetstore.unity.com/packages/tools/gui/… … Для двух записей в Google при поиске «Автономный файловый браузер Unity» ….

4. Спасибо! Я не знал, что мне нужно искать автономный файловый браузер. Я искал выбранную текстуру во время выполнения в finder/explorer и не нашел ничего полезного.

Ответ №1:

Если кого-то интересует решение: я использовал https://github.com/gkngkc/UnityStandaloneFileBrowser и адаптировал сценарий таким образом:

 using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using SFB;

[RequireComponent(typeof(Button))]
public class CanvasSampleOpenFileImage : MonoBehaviour, IPointerDownHandler
{
    public GameObject output;

#if UNITY_WEBGL amp;amp; !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);
    }

    // Called from browser
    public void OnFileUpload(string url) {
        StartCoroutine(OutputRoutine(url));
    }
#else
    //
    // Standalone platforms amp; editor
    //
    public void OnPointerDown(PointerEventData eventData) { }

    void Start()
    {
        var button = GetComponent<Button>();
        button.onClick.AddListener(OnClick);
    }

    private void OnClick()
    {
        var extensions = new[] {
            new ExtensionFilter("Image Files", "png", "jpg", "jpeg" )
        };
        var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", extensions, false);
        if (paths.Length > 0)
        {
            StartCoroutine(OutputRoutine(new System.Uri(paths[0]).AbsoluteUri));
        }
    }
#endif

    private IEnumerator OutputRoutine(string url)
    {
        var loader = new WWW(url);
        yield return loader;
        output.GetComponent<Renderer>().material.mainTexture = loader.texture;
        output.GetComponent<Renderer>().material.mainTextureScale = new Vector2(-1, -1);
    }
}
 

Просто прикрепите игровой объект к сценарию или определите его с помощью GameObject.Найдите, и текстура изменится во время выполнения с изображением, выбранным в любом месте с вашего компьютера.