c# – I’m gettin Null Reference in Unity and don’t know why

Here is the error

NullReferenceException: Object reference not set to an instance of an object

Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckReadAndThrow (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <13e6546058e340ada820e34dce3b245e>:0)
Unity.Collections.NativeList`1[T].get_Length() (at Library/PackageCache/com.unity.collections@1.2.4/Unity.Collections/NativeList.cs:227)
Unity.Networking.Transport.NetworkDriver+Concurrent.BeginSend (Unity.Networking.Transport.NetworkPipeline pipe, Unity.Networking.Transport.NetworkConnection id, Unity.Networking.Transport.DataStreamWriter& writer, System.Int32 requiredPayloadSize) (at Library/Pache) com.unity.transport@1.1.0/Runtime/NetworkDriver.cs:177)
Unity.Networking.Transport.NetworkDriver.BeginSend (Unity.Networking.Transport.NetworkConnection id, Unity.Networking.Transport.DataStreamWriter& writer, System.Int32 requiredPayloadSize) (at Library/PackageCache/com.unity.transport@1.1.0/Runtime /NetworkDriver.cs:1210)
Server.SendToClient (Unity.Networking.Transport.NetworkConnection connection, NetMessage msg) (at Assets/Scripts/Net/Server.cs:196) Chessboard.OnWelcomeServer (NetMessage msg, Unity.Networking.Transport.NetworkConnection cnn) (at Assets). Scripts/Chessboard.cs:774
NetWelcome.ReceivedOnServer (Unity.Networking.Transport.NetworkConnection cnn) (at Assets/Scripts/Net/NetMessage/NetWelcome.cs:32)
NetUtility.OnData (Unity.Networking.Transport.DataStreamReader stream, Unity.Networking.Transport.NetworkConnection cnn, Server server) (at Assets/Scripts/Net/NetUtility.cs:32)
Server.UpdateMessagePump() (at Assets/Scripts/Net/Server.cs:133)
Server.Update() (at Assets/Scripts/Net/Server.cs:121)

Code:

using Unity.Collections;
using System;
using Unity.Networking.Transport;
using UnityEngine;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;

public class Server : MonoBehaviour
{
    public string GetLocalIpAddress()
    {
            UnicastIPAddressInformation mostSuitableIp = null;

            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var network in networkInterfaces)
            {
                if (network.OperationalStatus != OperationalStatus.Up)
                    continue;

                var properties = network.GetIPProperties();

                if (properties.GatewayAddresses.Count == 0)
                    continue;

                foreach (var address in properties.UnicastAddresses)
                {
                    if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                        continue;

                    if (IPAddress.IsLoopback(address.Address))
                        continue;

                    if (!address.IsDnsEligible)
                    {
                        if (mostSuitableIp == null)
                            mostSuitableIp = address;
                        continue;
                    }

                    // The best IP is the IP got from DHCP server
                    if (address.PrefixOrigin != PrefixOrigin.Dhcp)
                    {
                        if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                            mostSuitableIp = address;
                        continue;
                    }

                return address.Address.ToString();
                }
            }

        return mostSuitableIp != null
            ? mostSuitableIp.Address.ToString()
            : "";
    }

    #region Singeton implementation
    public static Server Instance { set; get; }

    private void Awake()
    {
        Instance = this;
    }
    #endregion

    public NetworkDriver driver;
    private NativeList<NetworkConnection> connections;

    private bool isLocal = false;
    private bool isActive = false;
    private const float keepAliveTickRate = 20.0f;
    private float lastKeepAlive;

    public Action connectionDropped;

    // Methods
    public void Init(ushort port, bool localGame)
    {
        isLocal = localGame;
        driver = NetworkDriver.Create();
        NetworkEndPoint endPoint = NetworkEndPoint.Parse(GetLocalIpAddress(), port);
        Debug.Log("TEST Local: " + endPoint.Address);
        // endPoint.Port = port;
        if (driver.Bind(endPoint) != 0)
        {
            Debug.Log("Unable to bind op port" + endPoint.Port);
        }
        else
        {
            driver.Listen();
            Debug.Log("Currently listening on port" + endPoint.Port);
        }

        connections = new NativeList<NetworkConnection>(2, Allocator.Persistent);
        isActive = true;
    }
    public void Shutdown()
    {
        if (isActive)
        {
            driver.Dispose();
            connections.Dispose();
            isActive = false;
        }
    }
    public void OnDestroy()
    {
        Shutdown();
    }

    public void Update()
    {
        if (!isActive)
            return;
        KeepAlive();


        driver.ScheduleUpdate().Complete();
        CleanupConnections();
        AcceptNewConnection();
        UpdateMessagePump();
    }
    private void UpdateMessagePump()
    {
        DataStreamReader stream;
        for (int i = 0; i < connections.Length; i++)
        {
            NetworkEvent.Type cmd;
            while ((cmd = driver.PopEventForConnection(connections[i], out stream)) != NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    NetUtility.OnData(stream, connections[i], this);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log("Client disconnected from server");
                    connections[i] = default(NetworkConnection);
                    connectionDropped?.Invoke();
                    Shutdown(); // This is only if it is locah Host
                }
            }
        }
    }

    // Server specific
    private void KeepAlive()
    {
        if((Time.time - lastKeepAlive) > keepAliveTickRate)
        {
            lastKeepAlive = Time.time;
            Broadcast(new NetKeepAlive());
        }
    }
    private void CleanupConnections()
    {
        for (int i = 0; i < connections.Length; i++)
        {
            if (!connections[i].IsCreated)
            {
                connections.RemoveAtSwapBack(i);
                --i;
            }
        }
    }
    private void AcceptNewConnection()
    {
        NetworkConnection c;
        // Accept new connections
        if (isLocal == true)
        {
            if (connections.Length == 0)
            {
                while ((c = driver.Accept()) != default(NetworkConnection))
                {
                    connections.Add(c);
                    Debug.Log("New connection Added");
                }
            }
        }
        else if(isLocal == false)
        {   
            if(connections.Length <= 1)
            {
                while ((c = driver.Accept()) != default(NetworkConnection))
                {
                    connections.Add(c);
                    Debug.Log("New connection Added");
                }
            }
        }
    }
    public void SendToClient(NetworkConnection connection, NetMessage msg)
    {
        DataStreamWriter writer;
        driver.BeginSend(connection, out writer);
        msg.Serialize(ref writer);
        driver.EndSend(writer);
    }
    public void Broadcast(NetMessage msg)
    {
        for (int i = 0; i < connections.Length; i++)
            if (connections[i].IsCreated)
            {
            //    Debug.Log($"Sending {msg.Code} to : {connections[1].InternalId}");
                SendToClient(connections[i], msg);
            }
    }
}

Leave a Comment