Search Unity

How does this cause a NullReferenceException???

Discussion in 'Scripting' started by Rassettaja, Jan 11, 2019.

  1. Rassettaja

    Rassettaja

    Joined:
    Apr 2, 2016
    Posts:
    2
    Code (CSharp):
    1.  [Command]
    2.     public void CmdSwap(string net)
    3.     {
    4.         if(!isServer)
    5.         {
    6.             return;
    7.         }
    8.         Player _player;
    9.         _player = man.getplayer(net)
    10.         Swap swap;
    11.         swap = _player.GetComponentInChildren<Swap>();
    12.        Debug.log(_player.GetComponentInChildren<Swap>()) //Logs the correct gameobject
    13.         if(swap != null) {
    14.             swap.RpcSwap();
    15.             }
    16.     }
    Causes "NullReferenceException: Object reference not set to an instance of an object" at swap.RpcSwap().
    Also i can call other functions in "swap" just fine.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    3,684
    This would happen if .RpcSwap is actually a delegate (function pointer, System.Action, etc.) of some kind and it is still null. Do a:

    Code (csharp):
    1. Debug.Log( swap.RpcSwap.ToString());
    and see what that prints. If it prints something like "method group" then it's valid.
     
    Antistone likes this.
  3. Rassettaja

    Rassettaja

    Joined:
    Apr 2, 2016
    Posts:
    2
    Didn't try this but how i fixed it was i created a rpc function in the original script and then transferred everything from the cmd to the rpc and that fixed it.