I was watching Tom weiland video about connecting unity client to a dedicated server. I followed everything he scripted. I got to where he script UIManager and client, but i got a error and not sure how to fix it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public static UIManager instance;
public GameObject startMenu;
public InputField usernameField;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Debug.Log("Instance already exists, destroying object");
Destroy(this);
}
}
public void ConnectToServer()
{
startMenu.SetActive(false);
usernameField.interactable = false;
Client.instance.ConnectToServer();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System;
public class Client : MonoBehaviour
{
public static Client instance;
public static int dataBufferSize = 4096;
public string ip = "192.0.0.1";
public int port = 50500;
public int myid = 0;
public TCP tcp;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Debug.Log("Instance already exists, destroying object");
Destroy(this);
}
}
private void Start()
{
tcp = new TCP();
}
public void ConnnectToServer()
{
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)
{
return;
}
byte[] _data = new byte[_byteLength];
Array.Copy(receiveBuffer, _data, _byteLength);
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
}
catch
{
}
}
}
}