Liberi
An exergame built for kids with CP!
MinigameSpawner.cs
1 using UnityEngine;
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.Linq;
6 using System.Net;
7 using Lidgren.Network;
8 using LiberiNet;
9 using Janus;
10 
15 [Script(ScriptRole.Server)]
16 public class MinigameSpawner : MonoBehaviour
17 {
18  public Timeline<string> SpawnRequests;
19  public Timeline<GameMessage> ServerSpawns;
20 
21  const float TIMEOUT_DURATION = 5.0f;
22  bool _requestTimeout;
23 
24  void Awake ()
25  {
26  SpawnRequests = Sync.CreateEvent<string>();
27  ServerSpawns = Sync.CreateEvent<GameMessage>();
28  }
29 
30  void OnSpawn ()
31  {
32  SpawnRequests.EntryPassed += OnSpawnRequestReceived;
33  GameServer.Instance.ServerSpawned += OnServerSpawned;
34  GameServer.Instance.ServerSpawnFailed += OnServerSpawnFailed;
35  }
36 
37  void OnDestroy ()
38  {
39  if (GameServer.Instance != null)
40  {
41  GameServer.Instance.ServerSpawned -= OnServerSpawned;
42  GameServer.Instance.ServerSpawnFailed -= OnServerSpawnFailed;
43  }
44  }
45 
46  void OnSpawnRequestReceived (Timeline<string> timeline, TimelineEntry<string> entry)
47  {
48  if (!_requestTimeout)
49  {
50  GameServer.Instance.RequestServerSpawn(GameServerType.Minigame, entry.Value);
51  StartCoroutine(TimeoutAsync());
52  }
53  }
54 
55  void OnServerSpawned (GameServerType serverType, string mapId, IPEndPoint endPoint)
56  {
57  GameMessage msg = new GameMessage();
58  msg.Write((byte)serverType);
59  msg.Write(mapId);
60  msg.Write(endPoint);
61 
62  ServerSpawns[0] = msg;
63  }
64 
65  IEnumerator TimeoutAsync ()
66  {
67  _requestTimeout = true;
68  yield return new WaitForSeconds(TIMEOUT_DURATION);
69  _requestTimeout = false;
70  }
71 
72  void OnServerSpawnFailed (GameServerType serverType, string mapId)
73  {
74  //TODO handle server spawn failed
75  Debug.Log(string.Format("Server spawn failed. ID: {1} Type: {0}.", serverType, mapId));
76  }
77 }
static GameServer Instance
Gets the sole instance of this game server.
Definition: GameServer.cs:95
Main game server class.
Definition: GameServer.cs:19
ServerSpawnedHandler ServerSpawned
Event fired when a requested server spawn is successful.
Definition: GameServer.cs:80
void RequestServerSpawn(GameServerType serverType, string mapId)
Sends a server spawn request to the world server.
Definition: GameServer.cs:467
ServerSpawnFailedHandler ServerSpawnFailed
Event fired when a requested server spawn fails.
Definition: GameServer.cs:84
A Component used to decouple the Server side logic of a minigame portal from the MinigamePortal class...
A class for serializing game data into a stream for propagation between objects and peers...
Definition: GameMessage.cs:14
This class server two main functions: 1) As a MonoBehaviour, it allows for network synchronization of...
Definition: Sync.cs:13