본문 바로가기
개발/Photon

유니티 C# 포톤 채팅 간단 구현 Photon Chat

by SPNK 2024. 3. 27.
반응형

패키지 임포트

 

Photon Chat | 네트워크 | Unity Asset Store

Get the Photon Chat package from Photon Engine and speed up your game development process. Find this & other 네트워크 options on the Unity Asset Store.

assetstore.unity.com

 

코드 작성

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Chat;
using ExitGames.Client.Photon;
using UnityEngine.UI;
using System.IO;
using System.Text.RegularExpressions;
using Photon.Pun;

public class PhotonManager : MonoBehaviour, IChatClientListener
{
	private ChatClient chatClient;
	private string userName;
	private string currentChannelName = "Channel 001";

	public Text chatText;

	public InputField inputField;

	private bool delay = false;

	WaitForSeconds waitForSeconds = new WaitForSeconds(0.1f);


	void Start()
	{
		Application.runInBackground = true;

		Initialize();
	}

	public void Initialize() //채팅 서버 연결
	{
		userName = "닉네임";
		currentChannelName = "Channel 001";

		chatClient = new ChatClient(this);
		chatClient.ChatRegion = "asia";
		chatClient.Connect("a0e02b55-5336-4fe9-aedc-8f54e4a5184a", "1.0", new AuthenticationValues(userName));

		StopAllCoroutines();
		StartCoroutine(CheckChatCoroution());

		Debug.Log("채팅 서버 연결 시도 중");
	}

	public void AddLine(string txt) //채팅 내역 업데이트
	{
		chatText += txt;
	}

	public void OnApplicationQuit()
	{
		if (chatClient != null)
		{
			chatClient.Disconnect();
		}
	}

	public void DebugReturn(ExitGames.Client.Photon.DebugLevel level, string message)
	{
		if (level == ExitGames.Client.Photon.DebugLevel.ERROR)
		{
			Debug.LogError(message);
		}
		else if (level == ExitGames.Client.Photon.DebugLevel.WARNING)
		{
			Debug.LogWarning(message);
		}
		else
		{
			Debug.Log(message);
		}
	}

	public void OnConnected()
	{
		Debug.Log("서버에 연결되었습니다.");

		chatClient.Subscribe(new string[] { currentChannelName }, 30);
	}

	public void OnDisconnected()
	{
		chatUI.SetActive(false);

		Debug.Log("서버에 연결이 끊어졌습니다.");
	}

	IEnumerator CheckChatCoroution()
	{
		if (chatClient != null)
		{
			chatClient.Service();
		}
		else
		{
			yield break;
		}

		yield return waitForSeconds;
		StartCoroutine(CheckChatCoroution());
	}


	public void Input_Button(string text) //메세지 전달
	{
		if (chatClient.State == ChatState.ConnectedToFrontEnd)
		{
			if (inputField.text.Trim().Length > 0)
			{
				if (!delay)
				{
					chatClient.PublishMessage(currentChannelName, inputField.text);

					inputField.text = "";

					delay = true;
					Invoke("Delay", 2f);
				}
			}
			else
			{
				inputField.text = "";
			}
		}
	}

	void Delay()
	{
		delay = false;
	}

	public void OnGetMessages(string channelName, string[] senders, object[] messages) //메세지 받음
	{
		for (int i = 0; i < messages.Length; i++)
		{
			AddLine(string.Format("<Color=#FFFF00>{0}</Color> : {1}", senders[i], messages[i].ToString()));
		}
	}

	public void OnUserSubscribed(string channel, string user)
	{
		throw new System.NotImplementedException();
	}

	public void OnUserUnsubscribed(string channel, string user)
	{
		throw new System.NotImplementedException();
	}

	public void OnChatStateChange(ChatState state)
	{
		Debug.Log("OnChatStateChange = " + state);
	}

	public void OnSubscribed(string[] channels, bool[] results)
	{
		Debug.Log(string.Format("채널 입장 ({0})", string.Join(",", channels)));
	}

	public void OnUnsubscribed(string[] channels)
	{
		Debug.Log(string.Format("채널 퇴장 ({0})", string.Join(",", channels)));
	}

	public void OnPrivateMessage(string sender, object message, string channelName)
	{
		Debug.Log("OnPrivateMessage : " + message);
	}

	public void OnStatusUpdate(string user, int status, bool gotMessage, object message)
	{
		Debug.Log("status : " + string.Format("{0} is {1}, Msg : {2} ", user, status, message));
	}
}
반응형

댓글