Search Unity

Class to load sprite from WWW, is this safe?

Discussion in 'Scripting' started by shopguy, Sep 17, 2014.

  1. shopguy

    shopguy

    Joined:
    Jan 12, 2013
    Posts:
    282
    I've never used Coroutines before so not sure what a good/safe pattern is. I'm making a custom "Facebook friends" list that needs to load images from URLs as the user scrolls through the list which may contain 1000+ friends. So this code will be invoked a lot.

    I've made this class that I'm thinking I will attach to the sprites in the list, and I will change the URL as needed (part of my infinite scrolling). Even without the rest of my code done yet, does this seem like a safe class in general to easily load images from URLs?

    If one or more of these coroutines are running and I destroy my list or load a new level, they will just stop/cancel/abort, correct? I've read that the HTTP download will not actually stop, which is fine by me, as long as my code doesn't keep running (trying to work with objects that no longer exist).

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(Sprite))]
    5. public class SpriteFromURL : MonoBehaviour
    6. {
    7.     public string URL = "";
    8.     string LoadedURL = "";
    9.  
    10.     void Update ()
    11.     {
    12.         if (URL == LoadedURL)
    13.             return;
    14.         LoadedURL = URL;
    15.         if (string.IsNullOrEmpty(URL))
    16.         {
    17.             GetComponent<SpriteRenderer>().sprite = null;
    18.             return;
    19.         }
    20.         StartCoroutine(LoadURL());
    21.     }
    22.    
    23.     IEnumerator LoadURL()
    24.     {
    25.         WWW www = new WWW(URL);
    26.         yield return www;
    27.         if (string.IsNullOrEmpty(www.error))
    28.         {
    29.             Texture2D texture = www.textureNonReadable;
    30.             GetComponent<SpriteRenderer>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    31.         }
    32.         else
    33.             GetComponent<SpriteRenderer>().sprite = null;
    34.     }
    35. }
    36.