Rik van Toorn
Rik van Toorn

Reputation: 15

TargetRpc executes on sender instead of target (Mirror unity)

I have this simple punch mechanic where I want the client that hits an object take away the ability to jump on the player they hit. For some reason the Debug.Log($"Target hit") gets printed on the correct client but the canJump boolean is changed to false on the playerOwned object of the sender of the Command and not the target. I'm using the mirror networking library.

I have this 2 functions in the script.

[Command]
private void CmdPunch()
{
   // Cast a sphere in the forward direction of the player
    RaycastHit hit;
    float sphereRadius = 0.5f; // Adjust the radius as needed
    if (Physics.SphereCast(transform.position, sphereRadius, steve.forward, out hit, 6))
    {

        // Check if the object hit is on the "Player" layer
        if (hit.collider.CompareTag("Player"))
        {
            // Get the parent GameObject of the hit collider
            GameObject hitParent = hit.collider.transform.parent.gameObject;

            // Get the NetworkIdentity of the hit parent GameObject
            NetworkIdentity hitNetworkIdentity = hitParent.GetComponent<NetworkIdentity>();

            if (hitNetworkIdentity != null)
            {
                // Get the NetworkConnectionToClient from the hit NetworkIdentity
                NetworkConnectionToClient hitConnection = hitNetworkIdentity.connectionToClient;

                // Now you can use hitConnection to perform further actions, such as reducing the player's speed
                if (hitConnection != null)
                {
                    // Call TargetPunch on the hit player
                    TargetPunch(hitConnection);
                }
            }
        }
    }
}

[TargetRpc]
public void TargetPunch(NetworkConnectionToClient target)
{
    Debug.Log($"Target hit");

    canJump = false;
}

Maybe I don't understand Commands and TargetRpc's correctly

Upvotes: 0

Views: 52

Answers (0)

Related Questions