- Home /
Question by
Hoang Le Huy · Jun 29, 2015 at 05:42 PM ·
c#unity 5networkingsocketchat
Chat system is not working
Hi everybody,
I've used this code but It is not working so anyone help me?
It broken in this line and it shows nullobject:
NetworkManager.singleton.client.Send((short) MyMessages.MyMessageTypes.CHAT_MESSAGE, msg);
Here is my code:
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
public class Chat : NetworkManager {
public class MyMessages
{
public enum MyMessageTypes
{
CHAT_MESSAGE = 1000
}
public class ChatMessage : MessageBase
{
public string message;
}
}
public List<string> chatHistory = new List<string>();
//Keeps track of current message
private string currentMessage = string.Empty;
// hook into NetworkManager client setup process
public override void OnStartClient(NetworkClient mClient)
{
base.OnStartClient(mClient); // base implementation is currently empty
mClient.RegisterHandler((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, OnClientChatMessage);
}
// hook into NetManagers server setup process
public override void OnStartServer()
{
base.OnStartServer(); //base is empty
NetworkServer.RegisterHandler((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, OnServerChatMessage);
}
private void OnGUI() {
GUILayout.BeginHorizontal(GUILayout.Width(250));
currentMessage = GUILayout.TextField(currentMessage);
if (GUILayout.Button("Send"))
{
if (!string.IsNullOrEmpty(currentMessage))
{
Debug.Log("a: "+ currentMessage);
MyMessages.ChatMessage msg = new MyMessages.ChatMessage();
msg.message = currentMessage;
// this.client.Send((short) MyMessages.MyMessageTypes.CHAT_MESSAGE, msg);
NetworkManager.singleton.client.Send((short) MyMessages.MyMessageTypes.CHAT_MESSAGE, msg);
currentMessage = string.Empty;
}
}
foreach (var msg in chatHistory)
{
GUILayout.Label(msg);
}
GUILayout.EndHorizontal();
}
private void OnServerChatMessage(NetworkMessage netMsg)
{
var msg = netMsg.ReadMessage<StringMessage>();
Debug.Log("New chat message on server: " + msg.value);
MyMessages.ChatMessage chat = new MyMessages.ChatMessage();
chat.message = msg.value;
if (msg.value == "Dam this game sucks")
{
return;
}
else
{
NetworkServer.SendToAll((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, chat);
}
}
private void OnClientChatMessage(NetworkMessage netMsg)
{
var msg = netMsg.ReadMessage<StringMessage>();
Debug.Log("New chat message on client: " + msg.value);
chatHistory.Add(msg.value);
}
}
Thanks.
Comment
Answer by Allsaveone · Aug 03, 2015 at 01:41 PM
Shouldnt your Msg Method use [Command]? i assume your issue is that your strings arent being sent to other players on your server?