Hello,
I am trying to destroy specific object on mouse1 click. I am using Unity MLAPI 0.1.0. When I spawn object (SpawnPuzzlePieceServerRpc), I save it’s network id into a NetworkVariable. Object then follows mouse cursor (MakeActivePuzzlePieceFollowMouseServerRpc). After that, if I press mouse 1 button, I want that spawned object to be destroyed. Method (DeleteActivePuzzlePieceServerRpc) destroys object both on host and client, however, method continues to be called for some reason, and throws KeyNotFoundException: The given key was not present in the dictionary. NetworkVariable (activePuzzlePieceNetId) seems to be updated to 0 (because of the error throwned constantly), so the method shouldn’t be called again because of the condition in Update(). It feels like NetworkVariable is not syncing correctly here. What could be the problem and what am I doing wrong?
Thanks in advance,
public class PlayerTest : NetworkBehaviour
{
[SerializeField] Transform[] puzzlePiecePrefabs;
NetworkVariable<ulong> activePuzzlePieceNetId = new NetworkVariable<ulong>(0);
void Start()
{
activePuzzlePieceNetId.Settings.ReadPermission = NetworkVariablePermission.Everyone;
activePuzzlePieceNetId.Settings.WritePermission = NetworkVariablePermission.Everyone;
}
void Update()
{
if (!IsLocalPlayer) return;
if (!activePuzzlePieceNetId.Value.Equals(0))
{
if (Input.GetMouseButtonDown(1))
{
DeleteActivePuzzlePieceServerRpc();
}
else
{
MakeActivePuzzlePieceFollowMouseServerRpc();
}
}
}
[ServerRpc]
void DeleteActivePuzzlePieceServerRpc()
{
NetworkObject puzzlePiece = NetworkSpawnManager.SpawnedObjects[activePuzzlePieceNetId.Value];
Destroy(puzzlePiece.gameObject);
activePuzzlePieceNetId.Value = 0;
DeleteActivePuzzlePieceClientRpc();
}
[ClientRpc]
void DeleteActivePuzzlePieceClientRpc()
{
}
[ServerRpc]
public void SpawnPuzzlePieceServerRpc(int puzzlePieceId)
{
Transform puzzlePiece = Instantiate(puzzlePiecePrefabs[puzzlePieceId]);
puzzlePiece.GetComponent<NetworkObject>().SpawnWithOwnership(OwnerClientId);
activePuzzlePieceNetId.Value = puzzlePiece.GetComponent<NetworkObject>().NetworkObjectId;
SpawnPuzzlePieceClientRpc();
}
[ClientRpc]
void SpawnPuzzlePieceClientRpc()
{
}
[ServerRpc]
void MakeActivePuzzlePieceFollowMouseServerRpc()
{
MakeActivePuzzlePieceFollowMouseClientRpc();
}
[ClientRpc]
void MakeActivePuzzlePieceFollowMouseClientRpc()
{
NetworkObject puzzlePiece = NetworkSpawnManager.SpawnedObjects[activePuzzlePieceNetId.Value];
puzzlePiece.transform.position = GetMousePositionInWorld();
}
Vector3 GetMousePositionInWorld()
{
var mousePos = Input.mousePosition;
mousePos.z = 19;
return Camera.main.ScreenToWorldPoint(mousePos);
}
}