Netcode - KeyNotFoundException

Hello!
I am developing a game encountering Inventory, when I tried to drop things out, this happens:

KeyNotFoundException: The given key 'Inventory' was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <c0b7b90d34a54066a7234dad69255116>:0)
Unity.Netcode.NetworkBehaviour.__endSendServerRpc (Unity.Netcode.FastBufferWriter& bufferWriter, System.UInt32 rpcMethodId, Unity.Netcode.ServerRpcParams serverRpcParams, Unity.Netcode.RpcDelivery rpcDelivery) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.9.1/Runtime/Core/NetworkBehaviour.cs:127)
Inventory.DropServerRpc (System.Int32 index, UnityEngine.Vector3 pos) (at Assets/Scripts/Inventory/Inventory.cs:90)
Inventory.Drop () (at Assets/Scripts/Inventory/Inventory.cs:77)
Inventory.Update () (at Assets/Scripts/Inventory/Inventory.cs:70)

Here’s the code:

public void Drop()
{
    if (IsServer) DropServer(selectedSlot, PlayerController.Instance.transform.position);
    else DropServerRpc(selectedSlot, PlayerController.Instance.transform.position);
}

public void DropServer(int index, Vector3 pos)
{
    var r = slots[index].GetComponentInChildren<InventoryItem>().item.model.GetComponent<NetworkObject>().InstantiateAndSpawn(
        NetworkManager, position: pos);
    DropClientRpc(r);
}

[ServerRpc(RequireOwnership = false)]
public void DropServerRpc(int index, Vector3 pos)
{
    DropServer(index, pos);
}

How can I fix it?

By figuring out why “Inventory” is not a key in the dictionary. :wink:

You can use the debugger to analyze the code for such issues.

If you code like this, you’ll be in a hell of pain when you want to a) make changes or b) figure out exceptions and c) reliability.

There’s about five managed reference, any of which could be null at some time. There’s no guarantee which InventoryItem the GetComponentInChildren returns if there happen to be multiple. And if it’s one, you get that once and use the reference rather than getting it every time looking through all children.

1 Like