- Home /
Question by
Atarius · May 17, 2016 at 08:47 PM ·
networkingnullreferenceexceptionchat
Help with multiplayer chat functionality, null reference exception using networkmanager
Following an example I found online, this code is supposed to give simple chat functionality to a game. I am getting a null reference exception from one line of code and I was hoping someone could help me resolve the issue. It results in nothing being sent in the chat.
This is the line of code causing the issue around 40-45:
NetworkLobbyManager.singleton.client.Send((short) MyMessages.MyMessageTypes.CHAT_MESSAGE, msg);
Help would be greatly appreciated, thanks in advance.
//---------------BEGIN CHAT CODE---------------------//
public class MyMessages
{
public enum MyMessageTypes
{
CHAT_MESSAGE = 1000
}
public class ChatMessage : MessageBase
{
public string message;
}
}
//--------------------Setup Client and Server---------------//
public override void OnStartClient(NetworkClient mClient)
{
base.OnStartClient(mClient);
mClient.RegisterHandler((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, OnClientChatMessage);
}
public override void OnStartServer()
{
base.OnStartServer();
NetworkServer.RegisterHandler((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, OnServerChatMessage);
}
//---------------------Chat Code---------------------------//
public List <string> chatHistory = new List<string> { };
//keep track of current message
private string currentMessage = string.Empty;
//SEND MESSAGE CODE
private void SendMessage()
{
if (!string.IsNullOrEmpty(currentMessage.Trim()))
{
MyMessages.ChatMessage msg = new MyMessages.ChatMessage();
msg.message = currentMessage;
NetworkLobbyManager.singleton.client.Send((short)MyMessages.MyMessageTypes.CHAT_MESSAGE, msg);
currentMessage = string.Empty;
}
}
// GUI CODE
private void OnGUI()
{
Top();
}
private void Top()
{
GUILayout.BeginHorizontal(GUILayout.Width(250));
currentMessage = GUI.TextField(new Rect(0, Screen.height - 20, 200, 20), currentMessage);
if (GUI.Button(new Rect(200, Screen.height-20,75,20),"Send"))
SendMessage();
GUILayout.EndHorizontal();
foreach (var msg in chatHistory)
GUILayout.Label(msg);
}
//NETWORK CODE
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);
}
Comment
Your answer
Follow this Question
Related Questions
Null Reference Exception when using if(!islocalplayer) destroy 1 Answer
Chat system is not working 1 Answer
Unity Networking - Error on spawning Player 0 Answers
CHAT Multiplayer Problem 1 Answer