RoleMgr.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Networking;
  6. /* 内置角色信息管理者,(PK模式用到的角色选择) */
  7. public class RoleMgr
  8. {
  9. static string[] roleNames = {"海绵宝宝", "方狗狗", "五六七", "CHANEL", "Mimi", "喵了个咪"};
  10. public static int roleCount {
  11. get {
  12. return roleNames.Length;
  13. }
  14. }
  15. //获取角色信息(适用于本地PK获取对手或者我的信息)
  16. public static string GetRoleInfo(int id, Image image)
  17. {
  18. string nickname = null;
  19. if (IsRoleAvatar(id)) {
  20. nickname = roleNames[id - 1];
  21. } else {
  22. nickname = LoginMgr.myUserInfo.nickname;
  23. }
  24. SetAvatarToImage(image, id, LoginMgr.myUserInfo.avatarUrl);
  25. return nickname;
  26. }
  27. public static bool IsRoleAvatar(int id) {
  28. return id >= 1 && id <= 6;
  29. }
  30. public static int GetAvatarListLen() {
  31. return 7 + 24;
  32. }
  33. public const int NullAvatarID = int.MinValue;
  34. public static void SetAvatarToImage(Image image, int avatarID, string avatarUrl) {
  35. if (avatarID == NullAvatarID) image.sprite = null;
  36. else if (avatarID < 0) image.StartCoroutine(LoadAvatar(avatarUrl, image));
  37. else
  38. {
  39. string path = "Textures/Avatar/";
  40. if (avatarID < 7) path += "Player" + avatarID;
  41. else path += avatarID - 7;
  42. image.sprite = Resources.Load<Sprite>(path);
  43. }
  44. }
  45. //缓存网络图片,避免重复加载
  46. private static Dictionary<string, Sprite> remoteAvatarMap = new Dictionary<string, Sprite>();
  47. private static IEnumerator LoadAvatar(string url, Image image)
  48. {
  49. if (string.IsNullOrWhiteSpace(url))
  50. {
  51. image.sprite = null;
  52. yield break;
  53. }
  54. if (remoteAvatarMap.ContainsKey(url))
  55. {
  56. image.sprite = remoteAvatarMap[url];
  57. yield break;
  58. }
  59. image.sprite = null;
  60. using (UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET)) {
  61. uwr.downloadHandler = new DownloadHandlerTexture();
  62. yield return uwr.SendWebRequest();
  63. if (uwr.result != UnityWebRequest.Result.Success) yield break;
  64. Texture2D texture = DownloadHandlerTexture.GetContent(uwr);
  65. Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
  66. remoteAvatarMap[url] = sprite;
  67. image.sprite = sprite;
  68. }
  69. }
  70. }