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

提供: 初心者エンジニアの簡易メモ
ナビゲーションに移動 検索に移動
編集の要約なし
編集の要約なし
10行目: 10行目:
public class PhotonChatManager : MonoBehaviour, IChatClientListener
public class PhotonChatManager : MonoBehaviour, IChatClientListener
{
{
    static PhotonChatManager mInstance;
static PhotonChatManager mInstance;


public string channelName;
public string channelName;
16行目: 16行目:


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


36行目: 36行目:
}
}
public void SetScene(ChatConnectScene obj)
public void SetScene(ChatConnectScene obj)
    {
{
scene = obj;
scene = obj;
    }
}


public void Start()
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 (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
#if !UNITY_WEBGL
chatClient.UseBackgroundWorkerForSending = true;
chatClient.UseBackgroundWorkerForSending = true;
57行目: 57行目:
// authValues.UserId = UserManager.Instance.GetName();
// authValues.UserId = UserManager.Instance.GetName();
authValues.AuthType = Photon.Chat.CustomAuthenticationType.None;
authValues.AuthType = Photon.Chat.CustomAuthenticationType.None;
        Debug.Log("Connect " + PhotonNetwork.PhotonServerSettings.ChatAppID);
Debug.Log("Connect " + PhotonNetwork.PhotonServerSettings.ChatAppID);
        chatClient.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, "4.2", authValues); // PhotonNetwork.PhotonServerSettings.ChatAppID
chatClient.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, "4.2", authValues); // PhotonNetwork.PhotonServerSettings.ChatAppID
        channelName = "channelWorld"; // PhotonNetwork.room.Name
channelName = "channelWorld"; // PhotonNetwork.room.Name
    }
}
    void Update()
void Update()
    {
{
        if (chatClient != null) chatClient.Service();
if (chatClient != null) chatClient.Service();
}
}
// みんなに送信
// みんなに送信
126行目: 126行目:
Debug.Log(sender + ": " + msg);
Debug.Log(sender + ": " + msg);
if (scene != null)
if (scene != null)
            {
{
scene.OnChatRecord(sender, msg, i + 1, msgCount);
scene.OnChatRecord(sender, msg, i + 1, msgCount);
}
}
146行目: 146行目:
Debug.Log("Suscribed to channel");
Debug.Log("Suscribed to channel");
if (scene != null)
if (scene != null)
        {
{
scene.OnRoomEnter();
scene.OnRoomEnter();
}
}
188行目: 188行目:


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


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


void InitGui()
void InitGui()

2021年1月5日 (火) 13:19時点における版

サンプル

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.UserId = UserManager.Instance.GetName();
		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");
	}

}

参考

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