ChatUI.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class ChatUI : MonoBehaviour
  6. {
  7. public GameObject chatItemPrefab;
  8. public Transform chatParent;
  9. public static ChatUI instance;
  10. public InputField chatInputField;
  11. public Button sendBtn;
  12. void Awake()
  13. {
  14. instance = this;
  15. //PURGE
  16. foreach(Transform t in chatParent.GetComponentInChildren<Transform>())
  17. {
  18. if(t != chatItemPrefab) { Destroy(t.gameObject); }
  19. }
  20. sendBtn.onClick.AddListener(SendMsg);
  21. chatInputField.onEndEdit.AddListener(SendMsg);
  22. }
  23. public void AddNewMessage(string message,bool isMe)
  24. {
  25. GameObject newChatItem = Instantiate(chatItemPrefab,chatParent);
  26. newChatItem.GetComponentInChildren<Text>().text = message;
  27. newChatItem.GetComponentInChildren<Text>().alignment = isMe ? TextAnchor.MiddleRight : TextAnchor.MiddleLeft;
  28. }
  29. public void SendMsg()
  30. {
  31. SendMsg("");
  32. }
  33. public void SendMsg(string msg)
  34. {
  35. MPChat.instance.SendMsg(chatInputField.text);
  36. chatInputField.text = "";
  37. }
  38. }