60 lines
1.7 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using QSB.Messaging;
using UnityEngine;
2020-03-04 21:46:16 +01:00
using UnityEngine.Networking;
namespace QSB.Events
{
public class PlayerJoin : NetworkBehaviour
{
public static readonly Dictionary<uint, string> PlayerNames = new Dictionary<uint, string>();
public static string MyName { get; private set; }
private MessageHandler<JoinMessage> _joinHandler;
2020-03-04 21:46:16 +01:00
private void Awake()
{
_joinHandler = new MessageHandler<JoinMessage>();
2020-03-04 21:46:16 +01:00
_joinHandler.OnClientReceiveMessage += OnClientReceiveMessage;
_joinHandler.OnServerReceiveMessage += OnServerReceiveMessage;
}
public void Join(string playerName)
{
MyName = playerName;
StartCoroutine(SendJoinMessage(playerName));
}
private IEnumerator SendJoinMessage(string playerName)
{
yield return new WaitUntil(() => NetPlayer.LocalInstance != null);
var message = new JoinMessage
2020-03-04 21:46:16 +01:00
{
PlayerName = playerName,
SenderId = NetPlayer.LocalInstance.netId.Value
2020-03-04 21:46:16 +01:00
};
if (isServer)
{
_joinHandler.SendToAll(message);
}
else
{
_joinHandler.SendToServer(message);
}
}
private void OnServerReceiveMessage(JoinMessage message)
2020-03-04 21:46:16 +01:00
{
_joinHandler.SendToAll(message);
}
private void OnClientReceiveMessage(JoinMessage message)
2020-03-04 21:46:16 +01:00
{
PlayerNames[message.SenderId] = message.PlayerName;
2020-03-04 21:46:16 +01:00
DebugLog.All(message.PlayerName, "joined!");
}
}
}