ChatTextManager.cs 2.9 KB

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