-
Notifications
You must be signed in to change notification settings - Fork 163
/
ExampleNetworkDiscovery.cs
59 lines (49 loc) · 1.68 KB
/
ExampleNetworkDiscovery.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Net;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(NetworkManager))]
public class ExampleNetworkDiscovery : NetworkDiscovery<DiscoveryBroadcastData, DiscoveryResponseData>
{
[Serializable]
public class ServerFoundEvent : UnityEvent<IPEndPoint, DiscoveryResponseData>
{
};
NetworkManager m_NetworkManager;
[SerializeField]
[Tooltip("If true NetworkDiscovery will make the server visible and answer to client broadcasts as soon as netcode starts running as server.")]
bool m_StartWithServer = true;
public string ServerName = "EnterName";
public ServerFoundEvent OnServerFound;
private bool m_HasStartedWithServer = false;
public void Awake()
{
m_NetworkManager = GetComponent<NetworkManager>();
}
public void Update()
{
if (m_StartWithServer && m_HasStartedWithServer == false && IsRunning == false)
{
if (m_NetworkManager.IsServer)
{
StartServer();
m_HasStartedWithServer = true;
}
}
}
protected override bool ProcessBroadcast(IPEndPoint sender, DiscoveryBroadcastData broadCast, out DiscoveryResponseData response)
{
response = new DiscoveryResponseData()
{
ServerName = ServerName,
Port = ((UnityTransport) m_NetworkManager.NetworkConfig.NetworkTransport).ConnectionData.Port,
};
return true;
}
protected override void ResponseReceived(IPEndPoint sender, DiscoveryResponseData response)
{
OnServerFound.Invoke(sender, response);
}
}