Unity multiplayer synchronous online - player position (Netcode for GameObjects)

Unity synchronization basic S/C

 

 Install the above plugin

Create a new empty component to add NetworkManager, and set the preset body that you want to generate the object 

 You only need to bind a unique id to a player, and all components under it share an id

Add NetworkRigidbody and Transform (transfer properties that need to be synchronized) components to it

Open multiple windows at the same time, multiple characters will appear, but all characters will move together

Because it contains common components, all components have the same value, so all components in B need to be disabled in A

Therefore, only local player cameras, input and monitoring are saved, and all network players are disabled

Note: At this time, it cannot be because the player is not a component in the scene, so the camera can only be obtained by using the label

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

public class PlayerSetup : NetworkBehaviour
{
    [SerializeField]
    private Behaviour[] componentsToDisable;

    private Camera sceneCamera;

    // Start is called before the first frame update
    void Start()
    {
        //非本地玩家组件禁用
        if(!IsLocalPlayer)
        {
            for (int i = 0; i < componentsToDisable.Length; i++) 
            {
                //禁用组件
                componentsToDisable[i].enabled = false;
            }
        }else
        {
            //获取maincamera
            sceneCamera= Camera.main;
            if (sceneCamera != null) 
            {
                sceneCamera.gameObject.SetActive(false);
            }
        }
    }

    // Update is called once per frame
    private void OnDisable()
    {
        if(sceneCamera!= null)
        {
            sceneCamera.gameObject.SetActive(true);
        }
    }
}

 Unity disables the operation of Client by default, rewrite the client method

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

namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
    [DisallowMultipleComponent]

    public class ClientNetworkTransform:NetworkTransform
    {
        //重载是否只能在服务器端授权的函数:false
        protected override bool OnIsServerAuthoritative()
        {
            return false;
        }
    }
}

 Delete the NetworkTransform and Rigidbody in the player, and the NetworkTransform in the camera

Camera and player add ClientNetworkTransform (rigidbody)

Guess you like

Origin blog.csdn.net/Theolulu/article/details/129823667