- Edited
I am working on following Tom Weiland's unity tutorial for multiplayer but converting it to Godot, however, I cannot seem to get the Client class to instantiate the object correctly.
using Godot;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
public class Client : Node
{
public static Client instance = null;
public static int dataBufferSize = 4096;
public string ip = "127.0.0.1";
public int port = 26950;
public int myId = 0;
public TCP tcp;
public override void _Ready()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
GD.Print("Instance already exists, destroying object!");
this.QueueFree();
}
}
private void _tree_entered()
{
tcp = new TCP();
}
public void ConnectToServer()
{
tcp.Connect();
}
public class TCP
{
public TcpClient socket;
private NetworkStream stream;
private byte[] receiveBuffer;
public void Connect()
{
socket = new TcpClient
{
ReceiveBufferSize = dataBufferSize,
SendBufferSize = dataBufferSize
};
receiveBuffer = new byte[dataBufferSize];
socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);
}
private void ConnectCallback(IAsyncResult _result)
{
socket.EndConnect(_result);
if (!socket.Connected)
{
return;
}
stream = socket.GetStream();
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
}
private void ReceiveCallback(IAsyncResult _result){
try
{
int _byteLength = stream.EndRead(_result);
if (_byteLength <= 0)
{
//TODO: disconnect client
return;
}
byte[] _data = new byte[_byteLength];
Array.Copy(receiveBuffer, _data, _byteLength);
//TODO: handle data
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
}
catch(Exception _ex)
{
GD.Print("Error receiving TCP data: " + _ex);
//TODO: disconnect client
}
}
}
}
With this code I get his error message:
E 0:00:02.236 void Client.ConnectToServer(): System.NullReferenceException: Object reference not set to an instance of an object.
<C++ Error> Unhandled exception
<C++ Source> C:\Users\patri\Desktop\Game Development\Hallow Bash\Hallow Bash\scripts\network\Client.cs:38 @ void Client.ConnectToServer()()
<Stack Trace> Client.cs:38 @ void Client.ConnectToServer()()
UI_Manager.cs:27 @ void UI_Manager._on_ConnectButton_pressed()()
Thanks in advance to anyone that thinks they can help.