Unity,File explorer 打开图片文件,并显示

定义一个RawImage 和一个按钮button, 此脚本挂在button 上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Load_Scence : MonoBehaviour
{
    
    
    string path;
    public RawImage rawImage;
    public void OpenFileExplor()
    {
    
    //3 parameters: 
        path = EditorUtility.OpenFilePanel("show all images(.png)","","png");
        StartCoroutine(GetTexture()); ;
    }

    IEnumerator GetTexture()
    {
    
    
        //create a web request,return all files end with png
        UnityWebRequest www = UnityWebRequestTexture.GetTexture("file:///"+path);

        yield return www.SendWebRequest();
        //wait 5second befor execute anycode below this statement.
        // yield return new WaitForSeconds(5);

        //has errors
        if (www.isNetworkError || www.isHttpError)
        {
    
    
            Debug.Log(www.error);
        }
        else {
    
    
            Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            rawImage.texture = myTexture;
        }

        
    }
}

猜你喜欢

转载自blog.csdn.net/kaixinjiaoluo/article/details/124545390
今日推荐