Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

NullReferenceException on instance of script

Discussion in 'Scripting' started by beasleydom, Jan 4, 2020.

  1. beasleydom

    beasleydom

    Joined:
    Dec 24, 2019
    Posts:
    3
    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.
    Code (CSharp):
    1. public static NetworkServer Instance { get; private set; }
    2.  
    3. public static void SendMessage(string text, NetDeliveryMethod deliveryMethod)
    4.     {
    5.         NetOutgoingMessage sendMsg = Instance.server.CreateMessage();
    6.         sendMsg.Write(text);
    7.         Instance.server.SendToAll(sendMsg, deliveryMethod);
    8.     }
    The second script, in a different scene calls it like this:
    Code (CSharp):
    1. public void SendColourMatchMessage()
    2.     {
    3.         NetworkServer.SendMessage("CMStart", NetDeliveryMethod.ReliableOrdered);
    4.     }
    The communication between scripts appears to work through debugging, but the line:
    Code (CSharp):
    1. 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.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    Where do you set the value of "Instance" ?
     
  3. beasleydom

    beasleydom

    Joined:
    Dec 24, 2019
    Posts:
    3
    I don't think it's referenced anywhere else apart from the aforementioned code, what would I set it to?
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    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.
     
    beasleydom likes this.
  5. beasleydom

    beasleydom

    Joined:
    Dec 24, 2019
    Posts:
    3
    Ah yes, this fixed it. Thanks
    Code (CSharp):
    1. Instance = this;