Unet有一个组件叫NetWorkManagerHUD,添加之后可以快速开启服务器客户端停止等等
但是项目上肯定是不可以用OnGui的,so你需要自己调用这几个开启服务器关闭服务器的方法
百度了一下,发现有源码,粘给大家看一下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine.Networking.Match;
namespace UnityEngine.Networking
{
[EditorBrowsable(EditorBrowsableState.Never), AddComponentMenu("Network/NetworkManagerHUD"), RequireComponent(typeof(NetworkManager))]
public class NetworkManagerHUD : MonoBehaviour
{
public NetworkManager manager;
[SerializeField]
public bool showGUI = true;
[SerializeField]
public int offsetX;
[SerializeField]
public int offsetY;
private bool m_ShowServer;
private void Awake()
{
this.manager = base.GetComponent<NetworkManager>();
}
private void Update()
{
if (!this.showGUI)
{
return;
}
if (!this.manager.IsClientConnected() && !NetworkServer.active && this.manager.matchMaker == null)
{
if (Application.platform != RuntimePlatform.WebGLPlayer)
{
if (Input.GetKeyDown(KeyCode.S))
{
this.manager.StartServer();
}
if (Input.GetKeyDown(KeyCode.H))
{
this.manager.StartHost();
}
}
if (Input.GetKeyDown(KeyCode.C))
{
this.manager.StartClient();
}
}
if (NetworkServer.active && this.manager.IsClientConnected() && Input.GetKeyDown(KeyCode.X))
{
this.manager.StopHost();
}
}
private void OnGUI()
{
if (!this.showGUI)
{
return;
}
int num = 10 + this.offsetX;
int num2 = 40 + this.offsetY;
bool flag = this.manager.client == null || this.manager.client.connection == null || this.manager.client.connect