woong's

Unity Image Cache 사용하기 본문

Develop/Unity

Unity Image Cache 사용하기

dlsdnd345 2016. 2. 13. 20:24
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Unity Image Cache 사용하기


​안녕하세요 . Unity 에서 페이스북 친구목록을 불러오는 과정에서 Unity UIScrollView 를 사용하게 되었습니다 . 

페이스북 api 를 통해서 친구목록을 불러와서 UIScrollView 뿌려 주니 아이템 셀이 삭제 될때마다 

이미지가 깜박이는 경우가 생겼습니다 . 처음에는 코루틴때문에 그런가 싶어서 Stop 코루틴으로 해결해 보려 했으나 ,

제 안드로이드 경험으로 생각해 봤을때 캐싱 처리가 안된거 같아 Cache 를 사용해서 처리 해보니 

이미지가 깜박이지 않고 잘 나오는것을 볼 수 있었습니다 .


http://studiofive27.com/index.php/unity-cached-web-images/


위 링크를 통해 들어가보면 Image CaChe 관련해서 작업해놓으신 분이 있습니다 .


이미지 캐싱을 사용하기 위한 클래스 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class WebTextureCache : MonoBehaviour
{
    private Dictionary<string, Texture2D> imageCache = new Dictionary<string, Texture2D> ();
    private Dictionary<string, WWW> requestCache = new Dictionary<string, WWW> ();
    private static WebTextureCache instance = null;
 
    /// <summary>
    /// Instantiates a global instance of this object in the scene
    /// </summary>
    /// <param name='name'>What to name the new global object </param>
    public static WebTextureCache InstantiateGlobal (string name = "WebTextureCache")
    {
        if (instance == null) {
            var gameobject = new GameObject (name);
            gameobject.AddComponent<WebTextureCache> ();
            instance = gameobject.GetComponent<WebTextureCache> ();
        }
 
        return instance;
    }
 
    public IEnumerator GetTexture (string url, Action<Texture2D> callback)
    {
        if (!this.imageCache.ContainsKey (url)) {
            int retryTimes = 3; // Number of time to retry if we get a web error
            WWW request;
            do {
                --retryTimes;
                if (!this.requestCache.ContainsKey (url)) {
                    // Create a new web request and cache is so any additional
                    // calls with the same url share the same request.
                    this.requestCache [url] = new WWW (url);
                }
 
                request = this.requestCache [url];
                yield return request;
 
                // Remove this request from the cache if it is the first to finish
                if (this.requestCache.ContainsKey (url)&& this.requestCache [url] == request) {
                    this.requestCache.Remove (url);
                }
            } while(request.error != null && retryTimes >= 0);
 
            // If there are no errors add this is the first to finish,
            // then add the texture to the texture cache.
            if (request.error == null && !this.imageCache.ContainsKey (url)) {
                this.imageCache [url] = request.texture;
            }
        }
 
        if (callback != null) {
            // By the time we get here there is either a valid image in the cache
            // or we were not able to get the requested image.
            Texture2D texture = null;
            this.imageCache.TryGetValue (url, out texture);
            callback (texture);
        }
    }
}

 

 

 

​캐싱 클래스는 사용하는 방법 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using UnityEngine;
using System.Collections;
 
public class WebImageDisplayCached : MonoBehaviour
{
    public UITexture sprite;
    public string imageUrl = "http://tinyurl.com/cds23w5";
 
    void Start ()
    {
        if (sprite == null) {
            sprite = GetComponent<UITexture> ();
            if (sprite == null) {
                return;
            }
        }
 
        var textureCache = WebTextureCache.InstantiateGlobal ();
        StartCoroutine (textureCache.GetTexture (imageUrl, LoadImage));
    }
 
    public void LoadImage (Texture2D texture)
    {
        if (texture != null) {
            Shader shader = Shader.Find ("Unlit/Transparent Colored");
            if (shader != null) {
                var material = new Material (shader);
                material.mainTexture = texture;
                sprite.material = material;
                sprite.color = Color.white;
                sprite.MakePixelPerfect ();
            }
        }
    }
}

 

 

 

위 코드에서 StartCoroutine (textureCache.GetTexture (imageUrl, LoadImage));

 

​이부분이 핵심 코드입니다 . 

첫번째 인자 : 받아올 이미지 Url  

두번째 인자 : 받아온 이미지를 넘겨줄 콜백 메서드 


위코드를 실행하면 Url 을 통해서 받아온 이미지를 LoadImage 파라미터로 넘겨주고 실행하는것을 

볼 수 있습니다 .


넘어온 이미지를 , Texture 를 통해서 보여주면 이쁘게 나오는 친구 목록을 볼 수 있습니다 .


'Develop > Unity' 카테고리의 다른 글

Unity New Admob 사용하기  (1) 2016.02.13
Unity Assets Image 불러오기  (0) 2016.02.13
Unity ScrollView Item 재사용 하기  (1) 2016.02.13
Unity ScrollView 사용하기  (0) 2016.02.13
Unity Dynamic Font 사용하기  (0) 2016.02.13
Comments