Search Unity

"Object reference not set to an instance of an object"

Discussion in 'Getting Started' started by Oskar_Kasprzak, Jul 21, 2017.

  1. Oskar_Kasprzak

    Oskar_Kasprzak

    Joined:
    Mar 26, 2016
    Posts:
    61
    Hi.

    I feel so ashamed for creating next topic with same title, but I feel like I am doing something really wrong here.

    So I am trying to do a simple tic-tac-toe game using built-in network system. When I spawn my objects with
    Code (csharp):
    1. NetworkServer.Spawn(go);
    it's all fine and it works.

    But it doesn't work on client side, as I get message that "tried to instantiate object without authority" (local player authority is set to true on prefab). I've read that I have to use this line of code when it's about client side:
    Code (csharp):
    1. NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
    but no success as I get "NullReferenceException: Object reference not set to an instance of an object". Can someone please explain it to me?

    Best regards.

    /edit
    Literally going crazy here. When I try to run this in the editor, I get this error after first object spawned. When I do "build and run" and run it as a server as well I don't get any errors, but I can put X 5 times and then it switches to O. When I replace "NetworkServer.SpawnWithClientAuthority to NetworkServer.Spawn it works like it should, just server doesn't get any information when client does something (when server instantiate something, it shows on client).
     
    Last edited: Jul 21, 2017
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Null Reference Exception happens when you try to access a method or property on an object that should conceivably exist, but that object itself is currently null. Check this out:
    Code (CSharp):
    1. // Exhibit A
    2. Person awesomeGuy = new Person();
    3. awesomeGuy.name = "Schneider21";
    4.  
    5. // Exhibit B
    6. Person guyInNeed;
    7. guyInNeed.name = "Oskar_Kasprzak";
    The first example works (assuming Person is a class and 'name' is a public property of that class) because not only is the variable awesomeGuy declared, it's also defined. The second example does not work because the variable is only declared, and not defined. Therefor, at the time I'm trying to access the 'name' property of guyInNeed, the variable is null. This throws a Null Reference Exception.

    As far as why this is happening in your particular case, I can't say without looking at more code. If the error is pointing to that exact line you posted, then it would seem NetworkServer is undefined (which doesn't sound right, because my bet is that SpawnWithClientAuthority is a static method). So I'm guessing the Null Reference Exception is actually pointing you to a different line.

    If possible, share the exact message you're getting (copy+paste) and as much of the script as is feasible, indicating what line the error is directing you to if it doesn't match up with what you're sharing here.
     
  3. Oskar_Kasprzak

    Oskar_Kasprzak

    Joined:
    Mar 26, 2016
    Posts:
    61
    @Schneider21
    Thanks for your reply. I was working on my code, trying different things and I think that now I got another problem.

    I was typing whole long post for 20min and then realised that I'll just check the editor. It was not about the script, but about attaching it to correct gameObjects... Changed it from "GameController" to "Player" (this one which is spawned with each player)

    Now I have other problem, not sure if its getting better or worse. Please don't mind my naming or the way I am doing it. I am trying to learn and understand, thats why I am going for 3d game. Here is my code:
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using System;
    6. using UnityEngine.Networking;
    7.  
    8. public class TriggerController : NetworkBehaviour
    9. {
    10.     public GameObject xMark;
    11.     public GameObject oMark;
    12.     Camera cam;
    13.     RaycastHit hit;
    14.  
    15.     void Start()
    16.     {
    17.         cam = Camera.main.GetComponent<Camera>();
    18.     }
    19.  
    20.  
    21.     void Update()
    22.     {
    23.         if (!isLocalPlayer)
    24.         {
    25.             return;
    26.         }
    27.             Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    28.         if (Physics.Raycast(ray, out hit))
    29.         {
    30.             Debug.Log(hit.collider.name);
    31.             if (Input.GetMouseButtonDown(0))
    32.             {
    33.                 if (hit.transform.CompareTag("trigger"))
    34.                 {
    35.                  
    36.                     CmdPlaceMark();
    37.                     }
    38.  
    39.                 }
    40.          
    41.         }
    42.     }
    43.  
    44.     [Command]
    45.     void CmdPlaceMark()
    46.     {
    47.  
    48.             if (!hit.transform.gameObject.GetComponent<TriggerController2>().isMarked) //every trigger (9 at all) has this boolean so when I place some mark, I can't place any mark anymore.
    49.             {
    50.                 if (GameController.currentTurn == GameController.Turn.X)
    51.                 {
    52.                 GameObject  go = (GameObject)Instantiate(xMark, hit.collider.transform);
    53.                 NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
    54.                 GameController.currentTurn = GameController.Turn.O;
    55.                 }
    56.                 else {
    57.  
    58.                 GameObject go = (GameObject)Instantiate(oMark, hit.collider.transform);
    59.                 NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
    60.                 GameController.currentTurn = GameController.Turn.X;
    61.                      }
    62.                 hit.transform.gameObject.GetComponent<TriggerController2>().isMarked = true;
    63.             }
    64.        }
    65. }
    66.  
    And that's where fun begin. When I play host role in the editor (not doing any builds) it works like it should, spawning objects, debugging win when it should etc. Same when I do build&run and play as a host.

    The thing is - when build is host, and editor is client... I can place marks on build(host) and it shows at editor(client), and when I click somewhere at editor, nothing happens(literally, no warning)... and doing the other way around - when editor is host and build is client... when I place mark via editor, it shows at build. When I press somewhere at client(build) I get error pointing at this line:
    Code (csharp):
    1.  if (!hit.transform.gameObject.GetComponent<TriggerController2>().isMarked)
    Whole line from console:
    Code (csharp):
    1.  
    2. NullReferenceException: Object reference not set to an instance of an object
    3. TriggerController.CmdPlaceMark () (at Assets/TriggerController.cs:47)
    4. TriggerController.InvokeCmdCmdPlaceMark (UnityEngine.Networking.NetworkBehaviour obj, UnityEngine.Networking.NetworkReader reader)
    5. UnityEngine.Networking.NetworkIdentity.HandleCommand (Int32 cmdHash, UnityEngine.Networking.NetworkReader reader) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkIdentity.cs:617)
    6. UnityEngine.Networking.NetworkServer.OnCommandMessage (UnityEngine.Networking.NetworkMessage netMsg) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:1281)
    7. UnityEngine.Networking.NetworkConnection.HandleReader (UnityEngine.Networking.NetworkReader reader, Int32 receivedSize, Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:469)
    8. UnityEngine.Networking.NetworkConnection.HandleBytes (System.Byte[] buffer, Int32 receivedSize, Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:425)
    9. UnityEngine.Networking.NetworkConnection.TransportReceive (System.Byte[] bytes, Int32 numBytes, Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkConnection.cs:576)
    10. UnityEngine.Networking.NetworkServer.OnData (UnityEngine.Networking.NetworkConnection conn, Int32 receivedSize, Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:738)
    11. UnityEngine.Networking.NetworkServer+ServerSimpleWrapper.OnData (UnityEngine.Networking.NetworkConnection conn, Int32 receivedSize, Int32 channelId) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:1866)
    12. UnityEngine.Networking.NetworkServerSimple.HandleData (Int32 connectionId, Int32 channelId, Int32 receivedSize, Byte error) (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServerSimple.cs:384)
    13. UnityEngine.Networking.NetworkServerSimple.Update () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServerSimple.cs:247)
    14. UnityEngine.Networking.NetworkServer.InternalUpdate () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:691)
    15. UnityEngine.Networking.NetworkServer.Update () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkServer.cs:642)
    16. UnityEngine.Networking.NetworkIdentity.UNetStaticUpdate () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkIdentity.cs:1090)

    Anyone? I bet I am just doing something wrong with server-client communication.
     
  4. Oskar_Kasprzak

    Oskar_Kasprzak

    Joined:
    Mar 26, 2016
    Posts:
    61
    Okey looks like I've made it. Now I got last problem. Raycasting from camera point. Doesn't matter who is the host - the host always have correct camera view (all players have same camera view). When clicking as client it gets some kind of offset, and marks don't get instantiated or are instantiated at wrong place (not where mouse cursor is). Could someone check this code, please? Even if I press on same spot (e.g. center of board) it gives me different values from "ray.orgin".

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using System;
    6. using UnityEngine.Networking;
    7.  
    8. public class TriggerController : NetworkBehaviour
    9. {
    10.     public GameObject xMark;
    11.     public GameObject oMark;
    12.     Camera cam;
    13.  
    14.  
    15.     void Start()
    16.     {
    17.  
    18.         cam = Camera.main.GetComponent<Camera>();
    19.  
    20.     }
    21.  
    22.  
    23.     void Update()
    24.     {
    25.         if (!isLocalPlayer)
    26.         {
    27.             return;
    28.         }
    29.  
    30.             if (Input.GetMouseButtonDown(0))
    31.             {
    32.             var mousePos = Input.mousePosition;
    33.                     CmdPlaceMark(mousePos);
    34.              }
    35.     }
    36.  
    37.     [Command]
    38.     void CmdPlaceMark(Vector3 mousePos)
    39.     {
    40.  
    41.         Debug.Log("coommand");
    42.         Ray ray = cam.ScreenPointToRay(mousePos);
    43.         RaycastHit hit;
    44.         Debug.Log(ray.origin);
    45.             if (Physics.Raycast(ray, out hit)) {
    46.             if(hit.transform.CompareTag("trigger")) {
    47.             Debug.Log(hit.transform.gameObject.GetComponent<TriggerController2>().isMarked);
    48.             if (!hit.transform.gameObject.GetComponent<TriggerController2>().isMarked)
    49.             {
    50.                 if (GameController.currentTurn == GameController.Turn.X)
    51.                 {
    52.                 GameObject  go = (GameObject)Instantiate(xMark, hit.collider.transform);
    53.                 NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
    54.                 GameController.currentTurn = GameController.Turn.O;
    55.                 }
    56.                 else {
    57.  
    58.                 GameObject go = (GameObject)Instantiate(oMark, hit.collider.transform);
    59.                 NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
    60.                 GameController.currentTurn = GameController.Turn.X;
    61.                      }
    62.                 hit.transform.gameObject.GetComponent<TriggerController2>().isMarked = true;
    63.            }
    64.         }
    65.         }
    66.     }
    67. }
    68.  
    69.  

    /edit maybe it's worth noticing that my board isn't perpendicular to camera view, it's at some angle.
     
    Last edited: Jul 22, 2017
  5. Oskar_Kasprzak

    Oskar_Kasprzak

    Joined:
    Mar 26, 2016
    Posts:
    61
  6. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Sounds like you're figuring it out and learning a lot along the way! Thanks for reporting back on your progress and indicating what solution worked for you!