How to load an image from URL with Unity?

后端 未结 6 1784
感情败类
感情败类 2020-12-10 06:05

Please save me from going crazy.

No matter how many times I google, I always end up with (usually deprecated) versions of the following code:

IEnumer         


        
6条回答
  •  暖寄归人
    2020-12-10 06:35

    You can do that with async/await:

    using System.Threading.Tasks;
    using UnityEngine;
    using UnityEngine.Networking;
    
    public static async Task GetRemoteTexture ( string url )
    {
        using( UnityWebRequest www = UnityWebRequestTexture.GetTexture( url ) )
        {
            //begin requenst:
            var asyncOp = www.SendWebRequest();
    
            //await until it's done: 
            while( asyncOp.isDone==false )
            {
                await Task.Delay( 1000/30 );//30 hertz
            }
    
            //read results:
            if( www.isNetworkError || www.isHttpError )
            {
                //log error:
                #if DEBUG
                Debug.Log( $"{ www.error }, URL:{ www.url }" );
                #endif
    
                //nothing to return on error:
                return null;
            }
            else
            {
                //return valid results:
                return DownloadHandlerTexture.GetContent( www );
            }
        }
    }
    

    Usage example:

    [SerializeField] string _imageUrl;
    [SerializeField] Material _material;
    Texture2D _texture;
    
    async void Start ()
    {
        _texture = await GetRemoteTexture( _imageUrl );
        _material.mainTexture = _texture;
    }
    
    void OnDestroy () => Dispose();
    public void Dispose () => Object.Destroy( _texture );// memory released, leak otherwise
    

提交回复
热议问题