What is the best way to send data from a client to the server using Mirror?
Hi guys! I've been working at this for a few weeks now (I know) and I've finally given in to my struggles. I'm new to Mirror and Networking as a whole, but not Unity. if I'm making some stupid mistake please let me know! Ok, here's my issue. I have a Player Health script and I have a function "Damage" that is being called from my wep script. I know that the function is being called properly (I check like a million times).
Some errors I get: Trying to send command w/o auth. I do not know why this is happening. The error comes from the line " CmdSyncHP(HP);" in the Damage function. I do know that clients cannot call cmds on other clients.
Some weird effects: When the host shots a client dmg is done and shown, when the client shoots a host/client it does nothing.
Here's my script:
using Mirror;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : NetworkBehaviour
{
[Header("Main")]
[SyncVar]
[SerializeField]int HP;
[Client]
public void Damage(int damage)
{
HP -= damage;
CmdSyncHP(HP);
}
[Command]
void CmdSyncHP(int Sync)
{
RpcSyncHP(Sync);
Debug.Log("Cmd HP");
}
[ClientRpc]
void RpcSyncHP(int Sync)
{
HP = Sync;
Debug.Log("Rpc HP");
}
}
This is on my player root object. The Player Identity game object is set to Observers and has Client Auth. I really do feel like there is something very simple that I did wrong. If you need further info please let me know! I've tried a million different ways and things. I'm all out of ideas! Thanks for your help! One last thing, this is my first time posting here!
Answer by Loles · Dec 21, 2020 at 05:48 PM
Hello, @Jenmar75 [SyncVar] Can not be modified on Client. You should alter it on server, and Mirror will automatically synchronize it with all the clients. So something like this should work using Mirror; using UnityEngine; using UnityEngine.UI;
public class PlayerHealth : NetworkBehaviour
{
[Header("Main")]
[SyncVar]
[SerializeField]int HP;
[Client]
public void Damage(int damage)
{
CmdSyncHP(damage);
}
[Command]
void CmdSyncHP(int damage)
{
HP -= damage;
}
}
Or you can detect, when player should be damaged on server (not on client), just change that [SyncVar] HP there and don't do this communication at all. This should be also preffered as the player can lie to you.
Your answer
Follow this Question
Related Questions
Unity Mirror OnStartServer spawn GameObjects 1 Answer
How do i get the two client's units to match up rather than be incorrect units? 1 Answer
Setting function to run on all clients but only work on the player that called it 0 Answers
Unet NetworkServer.spawn, correcting my workflow: Found no behaviour for incoming Command 1 Answer