반응형

안녕하세요.

유니티에서 포톤서버를 이용해서 채팅을 구현해보도록 하겠습니다.

일단 오브젝트를 생성합니다.

1. Panel

1-1. Scroll View

1-1-1 Viewport

1-1-1-1 Content

1-1-1-1-1 Text(TMP) (1)

1-1-2 Scrollbar Vertical

1-2 InputField (TMP)

2. ChatManager

 

ChatManager 스크립트는 다음과 같이 작성합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
 
public class ChatManager : MonoBehaviourPunCallbacks
{
    public GameObject m_Content;
    public TMP_InputField m_inputField;
 
    PhotonView photonview;
 
    GameObject m_ContentText;
 
    string m_strUserName;
 
 
    void Start()
    {
        Screen.SetResolution(960600false);
        PhotonNetwork.ConnectUsingSettings();
        m_ContentText = m_Content.transform.GetChild(0).gameObject;
        photonview = GetComponent<PhotonView>();
    }
 
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return) && m_inputField.isFocused == false)
        {
            m_inputField.ActivateInputField();
        }
    }
    public override void OnConnectedToMaster()
    {
        RoomOptions options = new RoomOptions();
        options.MaxPlayers = 5;
 
        int nRandomKey = Random.Range(0100);
 
        m_strUserName = "user" + nRandomKey;
 
        PhotonNetwork.LocalPlayer.NickName = m_strUserName;
        PhotonNetwork.JoinOrCreateRoom("Room1", options, null);
    }
 
    public override void OnJoinedRoom()
    {
        AddChatMessage("connect user : " + PhotonNetwork.LocalPlayer.NickName);
    }
 
    public void OnEndEditEvent()
    {
        if (Input.GetKeyDown(KeyCode.Return))
        {
            string strMessage = m_strUserName + " : " + m_inputField.text;
 
            photonview.RPC("RPC_Chat", RpcTarget.All, strMessage);
            m_inputField.text = "";
        }
    }
 
    void AddChatMessage(string message)
    {
        GameObject goText = Instantiate(m_ContentText, m_Content.transform);
 
        goText.GetComponent<TextMeshProUGUI>().text = message;
        m_Content.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
        
    }
 
    [PunRPC]
    void RPC_Chat(string message)
    {
        AddChatMessage(message);
    }
 
}
 
cs

반응형

+ Recent posts