Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache Images downloaded from the web #48

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions CommunityEntity.UI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public partial class CommunityEntity
private static List<GameObject> AllUi = new List<GameObject>();
private static Dictionary<string, GameObject> UiDict = new Dictionary<string, GameObject>();

private static Dictionary<string, Texture2D> WebImageCache = new Dictionary<string, Texture2D>();
private static Dictionary<string, List<UnityEngine.UI.RawImage>> requestingWebImages = new Dictionary<string, List<UnityEngine.UI.RawImage>>();

public static void DestroyServerCreatedUI()
{
foreach ( var go in AllUi )
Expand All @@ -24,6 +27,7 @@ public static void DestroyServerCreatedUI()

AllUi.Clear();
UiDict.Clear();
WebImageCache.Clear();
requestingTextureImages.Clear();
UnloadTextureCache();
}
Expand Down Expand Up @@ -446,6 +450,18 @@ private void GraphicComponentCreated( UnityEngine.UI.Graphic c, JSON.Object obj

private IEnumerator LoadTextureFromWWW( UnityEngine.UI.RawImage c, string p )
{
if(WebImageCache.ContainsKey(p)){
if(c != null) c.texture = WebImageCache[p];
yield break;
}
// add to the existing request Queue if one exists, if not create one and become the main coroutine that applies the texture at the end
if(requestingWebImages.ContainsKey(p)){
requestingWebImages[p].Add(c);
yield break;
}else{
requestingWebImages.Add(p, new List<UnityEngine.UI.RawImage>());
}

var www = new WWW( p.Trim() );

while ( !www.isDone )
Expand All @@ -463,14 +479,18 @@ private IEnumerator LoadTextureFromWWW( UnityEngine.UI.RawImage c, string p )

Texture2D texture = new Texture2D( 2, 2, TextureFormat.RGBA32, false );
www.LoadImageIntoTexture( texture );
if ( c == null )
{
Debug.Log( "Error downloading image: " + p + " (not an image)" );
www.Dispose();
yield break;

if(!WebImageCache.ContainsKey(p)) WebImageCache.Add(p, texture);
if(requestingWebImages[p].Count > 0){
foreach(var graphic in requestingWebImages[p]){
graphic.texture = texture;
}
}
requestingWebImages.Remove(p);

c.texture = texture;

if(!WebImageCache.ContainsKey(p)) WebImageCache.Add(p, texture);
www.Dispose();
}

Expand Down