How to move client object through RPC ?

using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : NetworkBehaviour
{
    private PlayerControls controls;
    // Start is called before the first frame update
    void Start()
    {
        controls = new PlayerControls();
        controls.Enable();
    }

    // Update is called once per frame
    void Update()
    {
        if(!IsOwner) return;
        MoveClientRpc();
    }
    [Rpc(SendTo.Server)]
    private void MoveClientRpc()
    {
        MoveThePlayerRpc();
    }
    [Rpc(SendTo.Owner)]
    private void MoveThePlayerRpc()
    {
        transform.Translate(controls.MovementMap.MovePlayer.ReadValue<float>(), transform.position.y, transform.position.z);
        print("hello");
    }
}

So what i do here is: client —> MoveClientRpc(); —> Server —> MoveThePlayerRpc() —> Client(server).
Its works on host but did not working on the client(did not moving but receiving “hello” message).

Your code is set up to do the following:

  • owner sends RPC to server (every frame!)
  • Server returns RPC to owner
  • thus: owner moves and non-owners don’t

Note that the way you set it up, you will also only use the input available when the owner received the RPC from the server.

I recommend going through a tutorial and other learning materials. You’ll learn about client authoritative movement with NetworkTransform for instance. And what ownership means in networking.

Thanks. I watching docs/videos so may be i`ll found something.
Sure i can use LocalTransformObject but want to do it through Rpc. Dunno that move box from a to b is so difficult =).

It isn’t. :slight_smile:

Though the first time doing it usually is because networking is a complex system. :wink:

Solved!

using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : NetworkBehaviour
{
    private PlayerControls controls;
    private float myFloat;
    // Start is called before the first frame update
    void Start()
    {
        controls = new PlayerControls();
        controls.Enable();
    }

    // Update is called once per frame
    void Update()
    {
        if (!IsOwner) return;
        myFloat = controls.MovementMap.MovePlayer.ReadValue<float>();
        MoveClientRpc(myFloat);
    }
    [Rpc(SendTo.Server)]
    private void MoveClientRpc(float myfloat)
    {
        transform.Translate(myfloat, transform.position.y, transform.position.z);
    }
}

Server cant read my inputs so i pass it through parameter.
Yes, its not optomazied but atleast i better understand Rpc!

1 Like