[UGUI]圖文混排(三):資源管理

1.圖文混排中的資源,主要是圖片。spa

2.所謂的資源管理,能夠分爲資源對象池和資源加載這兩部分。這裏是爲圖文混排單獨作一套資源管理,固然也能夠改成調用項目中的資源管理。code

 

RichTextResourceManager.cs對象

 1 using UnityEngine;  2 using System.Collections.Generic;  3 using UnityEngine.UI;  4 using System;  5 #if UNITY_EDITOR
 6 using UnityEditor;  7 #endif
 8 
 9 public enum RichTextResourceType 10 { 11  Image, 12 } 13 
14 public class RichTextResourceManager : CSharpSingletion<RichTextResourceManager> { 15 
16     private Dictionary<RichTextResourceType, List<GameObject>> typeGoDic = new Dictionary<RichTextResourceType, List<GameObject>>(); 17     private DefaultControls.Resources resources = new DefaultControls.Resources(); 18 
19     public void SetPoolObject(RichTextResourceType type, GameObject go) 20  { 21         if (!typeGoDic.ContainsKey(type)) 22  { 23             List<GameObject> goList = new List<GameObject>(); 24  goList.Add(go); 25  typeGoDic.Add(type, goList); 26  } 27         else
28  { 29  typeGoDic[type].Add(go); 30  } 31         go.SetActive(false); 32  } 33 
34     public GameObject GetPoolObject(RichTextResourceType type) 35  { 36         GameObject go = null; 37         if (typeGoDic.ContainsKey(type)) 38  { 39             if (typeGoDic[type].Count > 0) 40  { 41                 go = typeGoDic[type][0]; 42                 if (go) 43  { 44                     go.SetActive(true); 45  typeGoDic[type].Remove(go); 46                     return go; 47  } 48  } 49  } 50         go = CreatePoolObject(type); 51         return go; 52  } 53 
54     private GameObject CreatePoolObject(RichTextResourceType type) 55  { 56         GameObject go = null; 57         if (type == RichTextResourceType.Image) 58  { 59             go = CreateImage(); 60  } 61         return go; 62  } 63 
64     public void LoadSprite(string path, Action<Sprite> callback) 65  { 66 #if UNITY_EDITOR
67         Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>("Assets/" + path + ".png"); 68         if ((sprite != null) && (callback != null)) 69  { 70  callback(sprite); 71  } 72 #endif
73  } 74 
75     public void LoadSprite(string path, Action<Sprite[]> callback) 76  { 77 #if UNITY_EDITOR
78         Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath("Assets/" + path + ".png") as Sprite[]; 79         if ((sprites != null) && (callback != null)) 80  { 81  callback(sprites); 82  } 83 #endif
84  } 85 
86     public void SetSprite(string path, Image image) 87  { 88         LoadSprite(path, (Sprite sprite) => { image.sprite = sprite; }); 89  } 90 
91     private GameObject CreateImage() 92  { 93         GameObject go = DefaultControls.CreateImage(resources); 94         go.layer = LayerMask.NameToLayer("UI"); 95         Image image = go.GetComponent<Image>(); 96         image.raycastTarget = false; 97         return go; 98  } 99 }
相關文章
相關標籤/搜索