ChatTextManager.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using LitJson;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. public class ChatTextManager : MonoBehaviour
  7. {
  8. public int TextCount;
  9. private Vector2 initSize;
  10. public RectTransform parent;
  11. public Text text;
  12. public RectTransform rect;
  13. public ScrollRect scrollRect;
  14. public Text TextInfo;
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. initSize = parent.sizeDelta;
  19. }
  20. public void DeletText()
  21. {
  22. TextCount = 0;
  23. text.text = "";
  24. TextInfo.text = "信息-" + TextCount+"";
  25. }
  26. public void SetText(string msg)
  27. {
  28. TextCount++;
  29. text.text += "\n" + "\n" + msg;
  30. TextInfo.text = "信息-" + TextCount + "";
  31. scrollRect.verticalNormalizedPosition = 0f;
  32. }
  33. // Update is called once per frame
  34. void Update()
  35. {
  36. // 获取Text的Size
  37. Vector2 v2 = rect.rect.size;
  38. // width保持不变
  39. rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, v2.x);
  40. // 动态设置height
  41. rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, text.preferredHeight);
  42. if(initSize.y < v2.y)
  43. {
  44. parent.sizeDelta = rect.rect.size;
  45. }
  46. }
  47. public void joinRoom()
  48. {
  49. SetText("<color=yellow>您加入了房间</color>");
  50. }
  51. public void createRoom()
  52. {
  53. SetText("您创建了房间");
  54. }
  55. public void leaveRoom(string n)
  56. {
  57. SetText(n+" 离开了房间");
  58. }
  59. public void otherJoinRoom(string n)
  60. {
  61. SetText(n + " 加入了房间");
  62. }
  63. public void SetTextManager(string method,JsonData data)
  64. {
  65. switch(method)
  66. {
  67. case "joinRoom":
  68. joinRoom();
  69. if (data["room"]["users"].Count > 0)
  70. {
  71. for (int i = 0; i < data["room"]["users"].Count; i++)
  72. {
  73. otherJoinRoom(data["room"]["users"][i]["nickName"].ToString());
  74. }
  75. }
  76. break;
  77. case "closed":
  78. if (SCRtcFactory.Instance.mSCRtcPeers != null && !string.IsNullOrEmpty(data["peerId"].ToString()))
  79. {
  80. if (SCRtcFactory.Instance.mSCRtcPeers.getPeer(data["peerId"].ToString()) != null)
  81. {
  82. leaveRoom(SCRtcFactory.Instance.mSCRtcPeers.getPeer(data["peerId"].ToString()).name);
  83. }
  84. }
  85. break;
  86. case "joined":
  87. otherJoinRoom(data["nickName"].ToString());
  88. break;
  89. case "chatMessage":
  90. SetText(data["from"].ToString()+":"+ data["chatMessage"].ToString());
  91. break;
  92. }
  93. }
  94. }