유니티/Photon

Photon Chat 튜토리얼

민또배기 2022. 4. 20. 11:34
반응형

유니티 버전 : 2020.3.25f1(URP)

작업환경 : Mac (Monterey 12.3.1)

 

채팅기능을 만들기 위해 제일 먼저 Photon을 사용해보도록 하겠습니다.

근데 이것만 해도 다 될 것 같은 느낌...

 

Photon Korea에서 유튜브 영상으로 튜토리얼을 알려주고 계십니다... 하지만 오류들이 있죠 버전 차이 때문에 생기는 오류 같습니다.

https://www.youtube.com/watch?v=QdEJhjx5BZI 

 

오류해결은 좀 있다가 하기로 하고 차근차근 천천히 해봅시다.

 

생성한 유니티 프로젝트에서 Photon Chat Asset을 다운 받아주세요.

저는 일단 chat 기능만 확인해볼거라서 다른건 설치하지 않겠습니다.

 

https://assetstore.unity.com/packages/tools/network/photon-chat-45334

 

Photon Chat | 네트워크 | Unity Asset Store

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

assetstore.unity.com

 

그 뒤에 포톤 콘솔?로 이동해서 새 어플리케이션을 추가해줍니다.

https://dashboard.photonengine.com/ko-KR/

 

글로벌 크로스 플랫폼 실시간 게임 개발 | Photon Engine

Sign In 아직 계정이 없으신가요? 회원 등록은 여기를 클릭

id.photonengine.com

 

 

 

작성이 완료되면 아래처럼 CHAT이름을 가진 보드?가 하나 생성됩니다.

여기서 필요한 건 App ID 입니다.

복사한 App ID 값은 Asset 폴더 → Resources → ChatSettingFile 에 입력해주시면 됩니다.(하단 사진 참고)

 

여기 까지 되셨다면 일단 준비는 끝났습니다.

나머지는 유튜브 영상에 나와있는데로 진행하시면 됩니다.

InputField 와 Scroll View 생성하고 Scroll View 의 Content에 Text를 추가 합니다.

그리고 Text에는 Content Size Fitter 컴포넌트를 추가하고 Vertical Fit을 Preferred Size로 변경합니다.

 

ChatController에 추가할 스크립트를 작성합니다. 작성이 완료되면 추가해줍니다.

 

TextChat.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Chat;
using ExitGames.Client.Photon;

public class TestChat : MonoBehaviour, IChatClientListener
{
	private ChatClient chatClient;
	private string userName;
	private string currentChannelName;

	public InputField inputField;
	public Text outputText;

	// Use this for initialization
	void Start()
	{

		Application.runInBackground = true;

		userName = System.Environment.UserName;
		currentChannelName = "Channel 001";

		chatClient = new ChatClient(this);
		chatClient.Connect(ChatSettings.Instance.AppId, "1.0", new AuthenticationValues(userName));

		AddLine(string.Format("연결시도", userName));
	}

	
	public void AddLine(string lineString)
	{
		outputText.text += lineString + "\r\n";
	}

	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()
	{
		AddLine("서버에 연결되었습니다.");

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

	public void OnDisconnected()
	{
		AddLine("서버에 연결이 끊어졌습니다.");
	}

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

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

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

	public void OnGetMessages(string channelName, string[] senders, object[] messages)
	{
		for (int i = 0; i < messages.Length; i++)
		{
			AddLine(string.Format("{0} : {1}", senders[i], messages[i].ToString()));
		}
	}

	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));
	}

	void Update()
	{
		chatClient.Service();
	}

	public void Input_OnEndEdit(string text)
	{
		if (chatClient.State == ChatState.ConnectedToFrontEnd)
		{
			//chatClient.PublishMessage(currentChannelName, text);
			chatClient.PublishMessage(currentChannelName, inputField.text);

			inputField.text = "";
		}
	}

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

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

 

이 다음으로 InputField에 On End Edit에 ChatController를 추가하고 Input_OnEndEdit함수를 추가합니다.

 

그리고 실행한 뒤 InputField에 입력하면 아래처럼 동작을 확인할 수 있습니다.

하지만 한글은 맨 뒤에 한글자는 출력되지 않더라구요.. (스페이스바를 한번 더 눌러줍니다.)

 

# 근데 InputField에서 에러가 날 수 있습니다. 

# You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings. ~~~

위와 같은 에러가 나타났다면 Edit → Project Settings → Player → Other Settings → Configuration → Active Input Handling → Both로 변경합니다.

 

반응형