1.图文混排中的资源,主要是图片。
2.所谓的资源管理,可以分为资源对象池和资源加载这两部分。这里是为图文混排单独做一套资源管理,当然也可以改为调用项目中的资源管理。
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 }
原文地址:https://www.cnblogs.com/lyh916/p/9281816.html
时间: 2024-10-08 13:27:10