二、局域网联机

目录

1.下载资源包 

2.配置NetworkManager

3.编写测试UI


1.下载资源包 

二、局域网联机_第1张图片

二、局域网联机_第2张图片

2.配置NetworkManager

(1)在Assets/Prefabs下创建Network Prefabs List

二、局域网联机_第3张图片

相应设置如下: 

二、局域网联机_第4张图片

(2) 创建空物体“NetworkManager”并挂载NetworkManager组件。相应设置如下:

二、局域网联机_第5张图片

(3) 选择Player预制体并挂载组件Network Object

二、局域网联机_第6张图片

(4)在Asset/Scripts/目录下创建Network目录并创建并编写ClientNetworkTransform.cs,使Client可控制transform的属性,将其挂载至Player预制体

using Unity.Netcode.Components;
using UnityEngine;

namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
    [DisallowMultipleComponent]
    public class ClientNetworkTransform : NetworkTransform
    {
        protected override bool OnIsServerAuthoritative()
        {
            return false;
        }
    }
}

并进行如下设置

二、局域网联机_第7张图片

(5) 选择Player预制体并挂载组件Network Rigidbody

二、局域网联机_第8张图片

(6)将原有的Main Camera重命名(F2)为SceneCamera,并将其Tag设置为MainCamera

二、局域网联机_第9张图片

(7)在Player预制体上创建并编写PlayerSetup.cs,使游戏只接收本地输入

using UnityEngine;
using Unity.Netcode;

public class PlayerSetup : NetworkBehaviour
{
    [SerializeField] 
    private Behaviour[] componentsToDisable;
    [SerializeField] 
    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
        {
            sceneCamera=Camera.main;
            if (Camera.main != null)
            {
                sceneCamera.gameObject.SetActive(false);
            }
        }
    }

    private void OnDisable()
    {
        sceneCamera.gameObject.SetActive(true);
    }
}

 并对其进行如下设置

二、局域网联机_第10张图片

将其移动至Assets/Scripts/Player目录下 

3.编写测试UI

(1)创建Canvas并将其命名为MenuUI,并在其内部创建3个Button并分别命名为Host,Server以及Client。Hierarchy中的物体结构和UI布局如下:

二、局域网联机_第11张图片 二、局域网联机_第12张图片

(2)在NetworkManager上创建并编写NetworkManageUI.cs,编写按钮逻辑

using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

public class NetworkManagerUI : MonoBehaviour
{
    [SerializeField] 
    private Button hostBtn;
    [SerializeField] 
    private Button serverBtn;
    [SerializeField] 
    private Button clientBtn;
    
    // Start is called before the first frame update
    void Start()
    {
        hostBtn.onClick.AddListener(() =>
        {
            NetworkManager.Singleton.StartHost();
        });
        serverBtn.onClick.AddListener(() =>
        {
            NetworkManager.Singleton.StartServer();
        });
        clientBtn.onClick.AddListener(() =>
        {
            NetworkManager.Singleton.StartClient();
        });
    }
}

你可能感兴趣的:(#,unity,游戏引擎)