目录
1.下载资源包
2.配置NetworkManager
3.编写测试UI
1.下载资源包
2.配置NetworkManager
(1)在Assets/Prefabs下创建Network Prefabs List
相应设置如下:
(2) 创建空物体“NetworkManager”并挂载NetworkManager组件。相应设置如下:
(3) 选择Player预制体并挂载组件Network Object
(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;}}
}
并对其Syncing属性进行如下设置
(5) 选择Player预制体并挂载组件Network Rigidbody
(6)在Player预制体中的Camera上挂载Network Transform组件,并对其Syncing属性进行如下设置
(6)将原有的Main Camera重命名(F2)为SceneCamera,并将其Tag设置为MainCamera
(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 updatevoid 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);}
}
并对其进行如下设置
将其移动至Assets/Scripts/Player目录下
3.编写测试UI
(1)创建Canvas并将其命名为MenuUI,并在其内部创建3个Button并分别命名为Host,Server以及Client。Hierarchy中的物体结构和UI布局如下:
(2)在NetworkManager上创建并编写NetworkManageUI.cs,编写按钮逻辑,将其移至Assets/Scripts/Network
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 updatevoid Start(){hostBtn.onClick.AddListener(() =>{NetworkManager.Singleton.StartHost();});serverBtn.onClick.AddListener(() =>{NetworkManager.Singleton.StartServer();});clientBtn.onClick.AddListener(() =>{NetworkManager.Singleton.StartClient();});}
}
4.附录
测试效果图
(打包后,开启两个应用【其中一个作为主机端,另一个作为客户端】)
(其中一个应用,点击Host创建游戏)
(另一个应用,点击Client加入游戏)