Search code examples
c#unity-game-engineunity-networking

Unity Netcode for gameobjects: How to do player to player interactions?


I am doing a raycast from Player A and checking for another player B and then player A can interact with player B.

The Problem: When I trigger the interact function it only gets triggered for player A even though I am running interact function on player B. Also I am getting player B in the raycast but when I try to get its OwnerClientId it the same as the player A client Id.

My interaction code

private void Interact()
    {
        bool interacting = PlayerInputManager.Instance.IsInteracting();

        if (InteractionUI.Instance.IsInteracting(interacting, lookedAtInteractableObject != null))
        {
            if (lookedAtInteractableObject.TryGetComponent<IAmInteractable>(out IAmInteractable interactableItem))
            {
                if (lookedAtInteractableObject.TryGetComponent<PlayerToPlayerInteractions>(out PlayerToPlayerInteractions p2p))
                {
                    // This p2p.OwnerClientId is same as player A
                    interactableItem.Interact(playerScript, p2p.OwnerClientId);
                }
            }
        }
    }

My detection code

Ray ray = new Ray(cameraTransform.position, cameraTransform.forward);

        if (Physics.Raycast(ray, out RaycastHit hit, raycastMaxDistance, searchRaycastLM))
        {
            Debug.DrawRay(cameraTransform.position, cameraTransform.forward * raycastMaxDistance, Color.green);
            //? Player is looking at something here
            if (hit.collider.gameObject.TryGetComponent<IAmInteractable>(out IAmInteractable interactableItem))
            {
                //? Player is looking at item here
                lookedAtInteractableObject = hit.collider.gameObject;
                interactableItem.BeingLookedAt(cameraTransform);
            }
        }

Solution

  • Ok, I figured out the issue. I was getting the ID for player B, but I wasn't getting the ID for player A.

    If someone has a similar problem in the future I will try to explain it as best as I can.

    enter image description here

    Here are the steps for this problem

    1. Detect player B from player A
    2. Trigger interact function on player B but this will only trigger that function on Computer 1 so you need to send a RPC to server which will send a Client RPC to only Computer 2 and in that client RPC you will trigger some animation on Computer 2
    3. You will probably be using Client Network Animator to synchronize animations, and then you can set animation events to do some resetting of states.