Hello, I’m trying to make a code for calculating distance between two players on the server. My code doesn’t work. Maybe it is wrong at all…
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class DistanceCalculator : NetworkBehaviour {
[SyncVar] private Transform synctrans;
[SerializeField] Transform myTransform;
void FixedUpdate()
{
TransmitTransform();
}
[Command]
void CmdProvideTransformToServer(Transform trans)
{
synctrans = trans;
}
[ClientCallback]
void TransmitTransform()
{
CmdProvideTransformToServer(myTransform);
}
void Update()
{
float dist = Vector3.Distance(myTransform.position, synctrans.position);
print("Distance to other: " + dist);
}
ClientCallback should be an attribute of FixedUpdate, not TransmitTransform. Transmit transform should have a Client attribute.
You said you want your server to calculate the distance between 2 players, but you’re doing that in all the clients too. Update should have a ServerCallback attribute, and synctrans shouldn’t even be a SyncVar, unless you want to send the transform to clients too (that’s not what your question said, but maybe you do more than getting the distance).
Also, setting a syncvar value in FixedUpdate sounds like a bad idea, you either send too many sync events or most of them are just ignored. You’re trying to sync the transform several times per frame and only getting the distance once per frame, that looks really odd.
Also, for DistanceCalculator to be able to call a command (and actually running it on the server) it must be attached to an object with a NetworkIdentity with “Local Player Authority” checked. If you don’t mark that you won’t get an error, the command will just be ignored.