- Home /
RPC call ending up on wrong target
I hitted a speed-bump with Unity Networking. I am trying to implement a simple mechanic that damages player when he is close to an NPC.
Problem is that when I have server and client open, the server client is taking the damage IF it's been to vicinity of some NPC not the appropriate client.
Here is the relevant code inside NPCController attached to every NPC:
void DamageTarget()
{
if(Network.isServer)
{
networkView.RPC("GiveDamage", RPCMode.All, damage);
}
}
[RPC]
void GiveDamage(int damage)
{
currentTarget.GetComponent<PlayerController>().TakeDamage(damage);
}
currentTarget is set on server side after checking vicinity of NPCs:
void CheckTargets()
{
// Do the initial check for colliders within range
Collider[] hitColliders = Physics.OverlapSphere(transform.position, visibilityRadius);
for(int i = 0; i < hitColliders.Length; i++)
{
if(hitColliders[i].gameObject.CompareTag("Player"))
{
Debug.Log("Detected a player");
currentTarget = hitColliders[i].gameObject;
}
}
}
After hours of messing around, here's what I think it should be doing:
NPC objects on server keep track of their vicinity and if any player is found, it sets it as current target for that NPC.
If the player is in vicinity, the NPC controlled by server calls RPC function on the client that finds the currentTarget and calls it's TakeDamage function.
What am I doing wrong?
After giving it some more thought, I feel like I'm approaching it completely wrong and should handle everything, including keeping track of the health, server side and then just update the health on Player object with RPC call. What is the proper way to do such things?
Answer by 34638a · Jul 09, 2014 at 11:45 AM
If what I assume about your problem is correct your NPC's are looking for a player and if they find one they see one they are just broadcasting a message that says "Hey I found a player and you should do something" and no-one is listening.
The way you need to send the RPC is through a object that is on both the client and the server. we'll call this object ClientManager. On this object you need to have the scripts that the client will use to interact with the server, from here you have a Object to interact with the NPC's. Again call it NPCManager. This object receives commands from the NPC's to broadcast to the players, when it receives a command it send a int, string, boolean value, etc. to the ClientManager which in turn sends RPC's to the clients with the information you want to send.
by setting it up so there is a individual object to send and receive commands from the server to the clients, you can more easily interact between the server, NPC objects and the client players. all you need to do with the system above is set flags to check if that player is the intended recipient of the command.