「Unity/photon/pun1/chat」の版間の差分

提供: 初心者エンジニアの簡易メモ
ナビゲーションに移動 検索に移動
ページの作成:「==サンプル== using System.Collections; using System.Collections.Generic; using UnityEngine; using ExitGames.Client.Photon.Chat; using ExitGames.Client.Photon; p...」
 
Admin がページ「Unity/photon/chat」を「Unity/photon/pun1/chat」に、リダイレクトを残さずに移動しました
 
(同じ利用者による、間の8版が非表示)
1行目: 1行目:
==ライブラリ==
*photon_chatは不要。
*photon1についてるchatを使う。
==サンプル==
==サンプル==
using System.Collections;
PhotonChatManager.cs
using System.Collections.Generic;
<pre>
using UnityEngine;
using System.Collections;
using ExitGames.Client.Photon.Chat;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using UnityEngine;
public class ChatScript : MonoBehaviour, IChatClientListener {
using Photon.Chat;
public static ChatScript instance;
using ExitGames.Client.Photon;
public ChatClient chatClient;
 
private ConnectionProtocol connectionProtocol = ConnectionProtocol.Udp;
public class PhotonChatManager : MonoBehaviour, IChatClientListener
private ExitGames.Client.Photon.Chat.AuthenticationValues authValues = new ExitGames.Client.Photon.Chat.AuthenticationValues();
{
private string channelName;
static PhotonChatManager mInstance;
public string GetChannelName()
 
{
public string channelName;
return channelName;
public bool connectFlag = false;
}
 
// Use this for initialization
private ChatClient chatClient;
void Start () {
private ConnectionProtocol connectionProtocol = ConnectionProtocol.Udp;
//Singleton pattern
private Photon.Chat.AuthenticationValues authValues = new Photon.Chat.AuthenticationValues();
instance = this;
private ChatConnectScene scene;
chatClient = new ChatClient (this, connectionProtocol);
 
chatClient.ChatRegion = "EU";
private PhotonChatManager()
authValues.UserId = "guest1"; // PhotonNetwork.playerName;
{
authValues.AuthType = ExitGames.Client.Photon.Chat.CustomAuthenticationType.None;
}
chatClient.Connect(this.appId, "4.2", authValues); // PhotonNetwork.PhotonServerSettings.ChatAppID
public static PhotonChatManager Instance
channelName = "channel" ; // PhotonNetwork.room.Name
{
}
get
// Update is called once per frame
{
void Update () {
if (mInstance == null)
if (chatClient != null) chatClient.Service();
{
}
GameObject go = new GameObject("PhotonChatManager");
public void PublishMessage(string channelName, string message)
mInstance = go.AddComponent<PhotonChatManager>();
{
}
chatClient.PublishMessage(channelName, message);
return mInstance;
}
}
public void DebugReturn(DebugLevel level, string message)
}
{
public void SetScene(ChatConnectScene obj)
Debug.Log("Debug level "+ level);
{
Debug.Log("Message " + message);
scene = obj;
}
}
public void OnChatStateChange(ChatState state)
 
{
public void Start()
Debug.Log("Chat state: " + state);
{
}
if (string.IsNullOrEmpty(PhotonNetwork.PhotonServerSettings.ChatAppID))
public void OnConnected()
{
{
Debug.LogError("You need to set the chat app ID in the PhotonServerSettings file in order to continue.");
chatClient.Subscribe(new string[] { channelName });
return;
}
}
}
public void OnDisconnected()
public void Connect()
{
{
if (chatClient != null) chatClient.Disconnect();
chatClient = new ChatClient(this, connectionProtocol);
}
#if !UNITY_WEBGL
public void OnGetMessages(string channelName, string[] senders, object[] messages)
chatClient.UseBackgroundWorkerForSending = true;
{
#endif
int msgCount = messages.Length;
authValues.UserId = "guest1"; // PhotonNetwork.playerName;
for (int i = 0; i < msgCount; i++) {
authValues.AuthType = Photon.Chat.CustomAuthenticationType.None;
string sender = senders[i];
Debug.Log("Connect " + PhotonNetwork.PhotonServerSettings.ChatAppID);
string msg = (string)messages[i];
chatClient.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, "4.2", authValues); // PhotonNetwork.PhotonServerSettings.ChatAppID
Debug.Log(sender + ": " + msg);
channelName = "channelWorld"; // PhotonNetwork.room.Name
}
}
}
void Update()
public void OnPrivateMessage(string sender, object message, string channelName)
{
{
if (chatClient != null) chatClient.Service();
// throw new NotImplementedException();
}
}
// みんなに送信
public void OnStatusUpdate(string user, int status, bool gotMessage, object message)
public void PublishMessage(string channelName, string message)
{
{
Debug.Log("user: " + user);
chatClient.PublishMessage(channelName, message);
Debug.Log("status: " + status);
}
Debug.Log("gotMessage: " + gotMessage);
public enum Status
Debug.Log("message: " + message);
{
}
Offline,
public void OnSubscribed(string[] channels, bool[] results)
Online
{
}
Debug.Log("Suscribed to channel");
// ステータス設定(ChatUserStatus.Online,ChatUserStatus.Offline)
// sumple送信
public void SetOnlineStatus(Status statusMsg, string msg)
PublishMessage( channelName, "So Long, and Thanks for All the Fish!" );
{
}
int status = 0;
public void OnUnsubscribed(string[] channels)
if (statusMsg.Equals(Status.Offline))
{
{
Debug.Log("Unsubscribed");
status = ChatUserStatus.Offline;
}
}
  }
else if (statusMsg.Equals(Status.Online))
{
status = ChatUserStatus.Online;
}
chatClient.SetOnlineStatus(status, msg);
}
 
// IChatClientListener start
public void DebugReturn(DebugLevel level, string message)
{
Debug.Log("Debug level " + level);
Debug.Log("Message " + message);
}
public void OnChatStateChange(ChatState state)
{
Debug.Log("Chat state: " + state);
}
public void OnConnected()
{
Debug.Log("OnConnected");
// chatClient.Subscribe(new string[] { channelName });
chatClient.Subscribe(channelName, 0, 10); // 履歴10件保存
 
}
public void OnDisconnected()
{
Debug.Log("OnDisconnected");
if (chatClient != null) chatClient.Disconnect();
if (scene != null)
{
scene.OnDisconnected();
}
}
public void OnGetMessages(string channelName, string[] senders, object[] messages)
{
int msgCount = messages.Length;
Debug.Log("OnGetMessages msgCount=" + msgCount);
for (int i = 0; i < msgCount; i++)
{
string sender = senders[i];
string msg = (string)messages[i];
Debug.Log(sender + ": " + msg);
if (scene != null)
{
scene.OnChatRecord(sender, msg, i + 1, msgCount);
}
}
}
public void OnPrivateMessage(string sender, object message, string channelName)
{
Debug.Log("OnPrivateMessage");
}
public void OnStatusUpdate(string user, int status, bool gotMessage, object message)
{
Debug.Log("user: " + user);
Debug.Log("status: " + status);
Debug.Log("gotMessage: " + gotMessage);
Debug.Log("message: " + message);
}
public void OnSubscribed(string[] channels, bool[] results)
{
Debug.Log("Suscribed to channel");
if (scene != null)
{
scene.OnRoomEnter();
}
}
public void OnUnsubscribed(string[] channels)
{
Debug.Log("Unsubscribed");
foreach (string channel in channels)
{
Debug.Log("channel=" + channel);
}
}
 
public void OnUserSubscribed(string channel, string user)
{
Debug.LogFormat("OnUserSubscribed: channel=\"{0}\" userId=\"{1}\"", channel, user);
}
 
public void OnUserUnsubscribed(string channel, string user)
{
Debug.LogFormat("OnUserUnsubscribed: channel=\"{0}\" userId=\"{1}\"", channel, user);
}
// IChatClientListener end
 
}
</pre>
 
ChatConnectScene.cs
<pre>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
 
 
public class ChatConnectScene : MonoBehaviour
{
PhotonChatManager manager;
int chatMessageCnt = 0;
 
void Start()
{
manager = PhotonChatManager.Instance;
manager.SetScene(this);
manager.Connect();
InitGui();
}
 
// Update is called once per frame
void Update()
{
 
}
 
void InitGui()
{
GameObject.Find("SendButton").GetComponent<Button>().onClick.AddListener(OnClickSend);
OnChatRecord("Sys", "接続中...", 1, 1);
}
// メッセージイベント
public void OnChatRecord(string sender, string message, int num, int sumcnt)
{
Debug.Log("ChatRecordGui num=" + num + " sumcnt=" + sumcnt);
string panelName = "Panel";
for (int i = 0; i <= 9; i++)
{
Destroy(GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecordDummy" + i)); // dummyがあれば、削除
}
 
GameObject prefab = (GameObject)Resources.Load("ChatRecord");
GameObject content = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content");
 
Vector3 position = new Vector3(0, 0, 0);
if (sender != "" && message != "")
{
GameObject obj = Instantiate(prefab, position, Quaternion.identity, content.transform);
obj.name = "ChatRecord" + chatMessageCnt;
 
GameObject msgObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecord" + chatMessageCnt + "/MsgText");
GameObject nameObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecord" + chatMessageCnt + "/NameText");
msgObj.GetComponent<Text>().text = message;
nameObj.GetComponent<Text>().text = sender;
chatMessageCnt++;
}
if (num == sumcnt)
{
// 下に少し、スペース追加
GameObject prefabDummy = (GameObject)Resources.Load("ScoreDummyPanel");
GameObject objdummy = Instantiate(prefabDummy, position, Quaternion.identity, content.transform);
objdummy.name = "ChatRecordDummy" + Random.Range(0, 9);
}
Invoke("ScrollDown", 0.1f);
}
// 部屋に入るイベント
public void OnRoomEnter()
{
Debug.Log("RoomEnterGui");
OnChatRecord("Sys", "接続しました", 1, 1);
manager.connectFlag = true;
manager.SetOnlineStatus(PhotonChatManager.Status.Online, "");
Debug.Log("manager.connectFlag=" + manager.connectFlag);
}
public void OnDisconnected()
{
Debug.Log("OnDisconnected");
OnChatRecord("Sys", "接続が切れました。", 1, 1);
Invoke("Logout", 3f);
}
void Logout()
{
SceneManager.LoadScene("RoomSelectScene");
}
// スクロール下へ
public void ScrollDown()
{
string panelName = "Panel";
GameObject content = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content");
GameObject scrollObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/");
ScrollRect scroll = scrollObj.GetComponent<ScrollRect>();
scroll.verticalNormalizedPosition = 0;
content.GetComponent<ContentSizeFitter>().SetLayoutVertical();
 
}
void OnClickSend()
{
if (!manager.connectFlag) return;
GameObject textObj = GameObject.Find("InputField");
string msg = textObj.GetComponent<InputField>().text;
manager.PublishMessage(manager.channelName, msg);
textObj.GetComponent<InputField>().text = "";
}
void OnClickReturn()
{
manager.SetOnlineStatus(PhotonChatManager.Status.Offline, "Offline");
manager.OnDisconnected();
SceneManager.LoadScene("RoomSelectScene");
}
 
}
</pre>
 
=="The namespace 'Photon.Chat' already contains a definition for"エラーが出る場合==
以下エラーが出る場合
  Assets/PhotonChatApi/ChannelCreationOptions.cs(9,18): error CS0101: The namespace 'Photon.Chat' already contains a definition for 'ChannelCreationOptions'
 
以下2つあるのでどちらかを消す。かと思ったが、photon1についてるchatを使うので、そもそもphoton_chatはインストールしない
*Photon/PhotonChat/Code/ChannelCreationOption
*Photon/PhotonChatApi/ChannelCreationOption


一応上記で送信まで行けた。
以下エラーが出る場合
Assets/PhotonChatApi/ChannelWellKnownProperties.cs(9,18): error CS0101: The namespace 'Photon.Chat' already contains a definition for 'ChannelWellKnownProperties'


注意:PhotonUnityNetworkプラグインもimportするとAccountServiceクラスが2重になるなどのエラーが出る。
以下2つあるのでどちらかを消す。かと思ったが、photon1についてるchatを使うので、そもそもphoton_chatはインストールしない
*Photon/PhotonChat/Code/ChannelWelKnownProperties
*Photon/PhotonChatApi/ChannelWelKnownProperties


==参考==
==参考==
http://answers.unity3d.com/questions/1366044/unity-crashes-when-compiling-this-script-where-is.html
http://answers.unity3d.com/questions/1366044/unity-crashes-when-compiling-this-script-where-is.html

2021年8月11日 (水) 08:43時点における最新版

ライブラリ

  • photon_chatは不要。
  • photon1についてるchatを使う。

サンプル

PhotonChatManager.cs

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

public class PhotonChatManager : MonoBehaviour, IChatClientListener
{
	static PhotonChatManager mInstance;

	public string channelName;
	public bool connectFlag = false;

	private ChatClient chatClient;
	private ConnectionProtocol connectionProtocol = ConnectionProtocol.Udp;
	private Photon.Chat.AuthenticationValues authValues = new Photon.Chat.AuthenticationValues();
	private ChatConnectScene scene;

	private PhotonChatManager()
	{
	}
	public static PhotonChatManager Instance
	{
		get
		{
			if (mInstance == null)
			{
				GameObject go = new GameObject("PhotonChatManager");
				mInstance = go.AddComponent<PhotonChatManager>();
			}
			return mInstance;
		}
	}
	public void SetScene(ChatConnectScene obj)
	{
		scene = obj;
	}

	public void Start()
	{
		if (string.IsNullOrEmpty(PhotonNetwork.PhotonServerSettings.ChatAppID))
		{
			Debug.LogError("You need to set the chat app ID in the PhotonServerSettings file in order to continue.");
			return;
		}
	}
	public void Connect()
	{
		chatClient = new ChatClient(this, connectionProtocol);
#if !UNITY_WEBGL
		chatClient.UseBackgroundWorkerForSending = true;
#endif
		authValues.UserId = "guest1"; // PhotonNetwork.playerName;
		authValues.AuthType = Photon.Chat.CustomAuthenticationType.None;
		Debug.Log("Connect " + PhotonNetwork.PhotonServerSettings.ChatAppID);
		chatClient.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, "4.2", authValues); // PhotonNetwork.PhotonServerSettings.ChatAppID
		channelName = "channelWorld"; // PhotonNetwork.room.Name
	}
	void Update()
	{
		if (chatClient != null) chatClient.Service();
	}
	// みんなに送信
	public void PublishMessage(string channelName, string message)
	{
		chatClient.PublishMessage(channelName, message);
	}
	public enum Status
	{
		Offline,
		Online
	}
	// ステータス設定(ChatUserStatus.Online,ChatUserStatus.Offline)
	public void SetOnlineStatus(Status statusMsg, string msg)
	{
		int status = 0;
		if (statusMsg.Equals(Status.Offline))
		{
			status = ChatUserStatus.Offline;
		}
		else if (statusMsg.Equals(Status.Online))
		{
			status = ChatUserStatus.Online;
		}
		chatClient.SetOnlineStatus(status, msg);
	}

	// IChatClientListener start
	public void DebugReturn(DebugLevel level, string message)
	{
		Debug.Log("Debug level " + level);
		Debug.Log("Message " + message);
	}
	public void OnChatStateChange(ChatState state)
	{
		Debug.Log("Chat state: " + state);
	}
	public void OnConnected()
	{
		Debug.Log("OnConnected");
		// chatClient.Subscribe(new string[] { channelName });
		chatClient.Subscribe(channelName, 0, 10); // 履歴10件保存

	}
	public void OnDisconnected()
	{
		Debug.Log("OnDisconnected");
		if (chatClient != null) chatClient.Disconnect();
		if (scene != null)
		{
			scene.OnDisconnected();
		}
	}
	public void OnGetMessages(string channelName, string[] senders, object[] messages)
	{
		int msgCount = messages.Length;
		Debug.Log("OnGetMessages msgCount=" + msgCount);
		for (int i = 0; i < msgCount; i++)
		{
			string sender = senders[i];
			string msg = (string)messages[i];
			Debug.Log(sender + ": " + msg);
			if (scene != null)
			{
				scene.OnChatRecord(sender, msg, i + 1, msgCount);
			}
		}
	}
	public void OnPrivateMessage(string sender, object message, string channelName)
	{
		Debug.Log("OnPrivateMessage");
	}
	public void OnStatusUpdate(string user, int status, bool gotMessage, object message)
	{
		Debug.Log("user: " + user);
		Debug.Log("status: " + status);
		Debug.Log("gotMessage: " + gotMessage);
		Debug.Log("message: " + message);
	}
	public void OnSubscribed(string[] channels, bool[] results)
	{
		Debug.Log("Suscribed to channel");
		if (scene != null)
		{
			scene.OnRoomEnter();
		}
	}
	public void OnUnsubscribed(string[] channels)
	{
		Debug.Log("Unsubscribed");
		foreach (string channel in channels)
		{
			Debug.Log("channel=" + channel);
		}
	}

	public void OnUserSubscribed(string channel, string user)
	{
		Debug.LogFormat("OnUserSubscribed: channel=\"{0}\" userId=\"{1}\"", channel, user);
	}

	public void OnUserUnsubscribed(string channel, string user)
	{
		Debug.LogFormat("OnUserUnsubscribed: channel=\"{0}\" userId=\"{1}\"", channel, user);
	}
	// IChatClientListener end

}

ChatConnectScene.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;


public class ChatConnectScene : MonoBehaviour
{
	PhotonChatManager manager;
	int chatMessageCnt = 0;

	void Start()
	{
		manager = PhotonChatManager.Instance;
		manager.SetScene(this);
		manager.Connect();
		InitGui();
	}

	// Update is called once per frame
	void Update()
	{

	}

	void InitGui()
	{
		GameObject.Find("SendButton").GetComponent<Button>().onClick.AddListener(OnClickSend);
		OnChatRecord("Sys", "接続中...", 1, 1);
	}
	// メッセージイベント
	public void OnChatRecord(string sender, string message, int num, int sumcnt)
	{
		Debug.Log("ChatRecordGui num=" + num + " sumcnt=" + sumcnt);
		string panelName = "Panel";
		for (int i = 0; i <= 9; i++)
		{
			Destroy(GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecordDummy" + i)); // dummyがあれば、削除
		}

		GameObject prefab = (GameObject)Resources.Load("ChatRecord");
		GameObject content = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content");

		Vector3 position = new Vector3(0, 0, 0);
		if (sender != "" && message != "")
		{
			GameObject obj = Instantiate(prefab, position, Quaternion.identity, content.transform);
			obj.name = "ChatRecord" + chatMessageCnt;

			GameObject msgObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecord" + chatMessageCnt + "/MsgText");
			GameObject nameObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content/ChatRecord" + chatMessageCnt + "/NameText");
			msgObj.GetComponent<Text>().text = message;
			nameObj.GetComponent<Text>().text = sender;
			chatMessageCnt++;
		}
		if (num == sumcnt)
		{
			// 下に少し、スペース追加
			GameObject prefabDummy = (GameObject)Resources.Load("ScoreDummyPanel");
			GameObject objdummy = Instantiate(prefabDummy, position, Quaternion.identity, content.transform);
			objdummy.name = "ChatRecordDummy" + Random.Range(0, 9);
		}
		Invoke("ScrollDown", 0.1f);
	}
	// 部屋に入るイベント
	public void OnRoomEnter()
	{
		Debug.Log("RoomEnterGui");
		OnChatRecord("Sys", "接続しました", 1, 1);
		manager.connectFlag = true;
		manager.SetOnlineStatus(PhotonChatManager.Status.Online, "");
		Debug.Log("manager.connectFlag=" + manager.connectFlag);
	}
	public void OnDisconnected()
	{
		Debug.Log("OnDisconnected");
		OnChatRecord("Sys", "接続が切れました。", 1, 1);
		Invoke("Logout", 3f);
	}
	void Logout()
	{
		SceneManager.LoadScene("RoomSelectScene");
	}
	// スクロール下へ
	public void ScrollDown()
	{
		string panelName = "Panel";
		GameObject content = GameObject.Find("/Canvas/" + panelName + "/Scroll View/Viewport/Content");
		GameObject scrollObj = GameObject.Find("/Canvas/" + panelName + "/Scroll View/");
		ScrollRect scroll = scrollObj.GetComponent<ScrollRect>();
		scroll.verticalNormalizedPosition = 0;
		content.GetComponent<ContentSizeFitter>().SetLayoutVertical();

	}
	void OnClickSend()
	{
		if (!manager.connectFlag) return;
		GameObject textObj = GameObject.Find("InputField");
		string msg = textObj.GetComponent<InputField>().text;
		manager.PublishMessage(manager.channelName, msg);
		textObj.GetComponent<InputField>().text = "";
	}
	void OnClickReturn()
	{
		manager.SetOnlineStatus(PhotonChatManager.Status.Offline, "Offline");
		manager.OnDisconnected();
		SceneManager.LoadScene("RoomSelectScene");
	}

}

"The namespace 'Photon.Chat' already contains a definition for"エラーが出る場合

以下エラーが出る場合

Assets/PhotonChatApi/ChannelCreationOptions.cs(9,18): error CS0101: The namespace 'Photon.Chat' already contains a definition for 'ChannelCreationOptions'

以下2つあるのでどちらかを消す。かと思ったが、photon1についてるchatを使うので、そもそもphoton_chatはインストールしない

  • Photon/PhotonChat/Code/ChannelCreationOption
  • Photon/PhotonChatApi/ChannelCreationOption

以下エラーが出る場合

Assets/PhotonChatApi/ChannelWellKnownProperties.cs(9,18): error CS0101: The namespace 'Photon.Chat' already contains a definition for 'ChannelWellKnownProperties'

以下2つあるのでどちらかを消す。かと思ったが、photon1についてるchatを使うので、そもそもphoton_chatはインストールしない

  • Photon/PhotonChat/Code/ChannelWelKnownProperties
  • Photon/PhotonChatApi/ChannelWelKnownProperties

参考

http://answers.unity3d.com/questions/1366044/unity-crashes-when-compiling-this-script-where-is.html