NullReferenceException on instance of script

I’m making a multiplayer game using Lidgren and I am fairly new to unity. I have a couple of scripts that I need to communicate with one another through scenes, one of which is a server which can’t be repeatedly made as I need the server to stay constant throughout the scenes. In script A, the server, there is a method to send a message to all clients that requires some parameters and I added this in order to allow other scripts to access the method.

public static NetworkServer Instance { get; private set; }

public static void SendMessage(string text, NetDeliveryMethod deliveryMethod)
    {
        NetOutgoingMessage sendMsg = Instance.server.CreateMessage();
        sendMsg.Write(text);
        Instance.server.SendToAll(sendMsg, deliveryMethod);
    }

The second script, in a different scene calls it like this:

public void SendColourMatchMessage()
    {
        NetworkServer.SendMessage("CMStart", NetDeliveryMethod.ReliableOrdered);
    }

The communication between scripts appears to work through debugging, but the line:

NetOutgoingMessage sendMsg = Instance.server.CreateMessage();

throws a NullReferenceException:
NullReferenceException: Object reference not set to an instance of an object
NetworkServer.SendMessage (System.String text, Lidgren.Network.NetDeliveryMethod deliveryMethod) (at Assets/NetworkServer.cs:82)

I’m assuming this means there is no instance of the script, but I don’t exactly understand this and would appreciate any help.

Where do you set the value of “Instance” ?

I don’t think it’s referenced anywhere else apart from the aforementioned code, what would I set it to?

Hopefully you understand variables.

It’s of type NetworkServer, so it should be set to that. You didn’t post more of the script, but chances are you’re trying to create a singleton, so it needs to be set to to itself if it’s on the NetworkServer script.

1 Like

Ah yes, this fixed it. Thanks

Instance = this;