/// <summary> /// It will perform all necessary steps to serialize and save all configs from the entities on the current project /// </summary> private static void Save() { var prefabList = GetPrefabListFromBolt(); if (prefabList != null && prefabList.Count != 0) { var updateList = new List <UpdateItem>(); foreach (var prefabID in prefabList) { var go = PrefabDatabase.Find(prefabID); if (go != null) { var updateItem = BuildUpdateItem(go); if (updateItem != null) { updateList.Add(updateItem); } } } JsonSerializerUpdateUtils.SaveData(updateList, SerializedDataPath); BoltLog.Info("Save DONE!"); } else { BoltLog.Warn("No prefabs found to be serialized"); } }
public void ReceiveInput(string val) { if (_stopReceiveInput) { return; } var tempVal = _storedVal + val; if (tempVal.Length <= maxChars) { _storedVal = tempVal; //Trigger val added notifyValAdded?.Invoke(val); notifyVal?.Invoke(_storedVal); } if (_storedVal.Length == maxChars) { BoltLog.Warn($"{this} filled triggered | val: {_storedVal}"); _stopReceiveInput = true; notifyFilled?.Invoke(_storedVal); } }
// Utils private static IEnumerator ShutdownAndStartServer(int timeout = 10) { yield return(new WaitForSeconds(timeout)); BoltLog.Warn("No server found, restarting"); BoltNetwork.ShutdownImmediate(); }
static void NatUtility_OpenPort_Finish(NatDeviceState device, int port) { try { var natMapping = device.PortMappings.Values.FirstOrDefault(p => p.Internal == port && p.External == port); if (natMapping != null) { // set this port as open natMapping.Status = Bolt.NatPortMappingStatus.Open; // tell user about this portChanges.Enqueue(new NatPortMappingChanged { Device = device, Mapping = natMapping.Clone() }); // meep BoltLog.Info("Changed {0} on {1}", natMapping, device); } else { BoltLog.Warn("Received incorrect port mapping result from {0}", device); } } catch (Exception exn) { BoltLog.Exception(exn); } }
/// <summary> /// After scene is loaded, creates the Client Player, this player type will be different from the server player /// </summary> /// <param name="scene"></param> /// <param name="token"></param> public override void SceneLoadLocalDone(string scene, IProtocolToken token) { var serverPlayerToken = token as IntBoltToken; int playerType = 2; if (serverPlayerToken == null) { BoltLog.Warn("Null SceneLoadLocalDone token received"); } else { playerType = serverPlayerToken.intVal; } var spawnPosition = Vector3.zero; GameObject spawnPoint; BoltLog.Warn($"{this} Client | playerType: " + playerType); //playerType is the type of the server player, the client gets the other one //Example: if Server Player get the Morgue(type 2), Client will get the Cell (type 1) if (playerType == 1) { //Instantiate player at Morgue spawnPoint = GameObject.Find("SpawnPoint Morgue"); } else { //Instantiate player at Cell spawnPoint = GameObject.Find("SpawnPoint Cell"); } var clientPlayer = InstantiatePlayerAtSpawnPoint(spawnPoint); }
public override void Connected(BoltConnection connection) { BoltLog.Warn("Connected"); ServerAcceptToken acceptToken = connection.AcceptToken as ServerAcceptToken; if (acceptToken != null) { BoltLog.Info("AcceptToken: " + acceptToken.GetType()); BoltLog.Info("AcceptToken: " + acceptToken.data); } else { BoltLog.Warn("AcceptToken is NULL"); } ServerConnectToken connectToken = connection.ConnectToken as ServerConnectToken; if (connectToken != null) { BoltLog.Info("ConnectToken: " + connectToken.GetType()); BoltLog.Info("ConnectToken: " + connectToken.data); } else { BoltLog.Warn("ConnectToken is NULL"); } }
public override void ConnectRequest(UdpEndPoint endpoint, IProtocolToken token) { BoltLog.Warn("Connect Request"); //token should be ServerConnectToken if (token != null) { BoltLog.Warn(token.GetType().ToString()); ServerConnectToken t = token as ServerConnectToken; BoltLog.Warn("Server Token: null? " + (t == null)); BoltLog.Warn("Data: " + t.data); } else { BoltLog.Warn("Received token is null"); } ServerAcceptToken acceptToken = new ServerAcceptToken { data = "Accepted" }; BoltNetwork.Accept(endpoint, acceptToken); }
private void OnTriggerEnter2D(Collider2D other) { IDestroyable target; switch (other.tag) { case "Player": var player = other.gameObject.GetComponent <Player>(); if (player == null || player.playerId == shooter) { return; } target = player; break; case "Terrain": target = other.gameObject.GetComponent <IDestroyable>(); break; default: return; } if (target == null) { BoltLog.Warn("return with hitting an null object"); return; } target.OnHurt(dmg); BoltNetwork.Destroy(gameObject); }
public override void SceneLoadLocalDone(string scene, IProtocolToken token) { var serverPlayerToken = token as IntBoltToken; int playerType = 1; if (serverPlayerToken == null) { BoltLog.Warn("Null SceneLoadLocalDone token received"); } else { playerType = serverPlayerToken.intVal; } var spawnPosition = Vector3.zero; var spawnRotation = Quaternion.identity; GameObject spawnPoint; BoltLog.Warn($"{this} Server | playerType: " + playerType); if (playerType == 1) { //Instantiate player at Cell spawnPoint = GameObject.Find("SpawnPoint Cell"); } else { //Instantiate player at Morgue spawnPoint = GameObject.Find("SpawnPoint Morgue"); } //TODO: factory pattern var serverPlayer = InstantiatePlayerAtSpawnPoint(spawnPoint); }
public void OnUpdateBag(string bagContent) { BoltLog.Warn("sending update bag event"); var bagUpdateEvent = OnUpdateBagContent.Create(entity.Controller); bagUpdateEvent.BagContent = bagContent; bagUpdateEvent.Send(); }
IEnumerator UpdateHostInfoRoutine(System.Object protocolToken) { var t = new Timer(ROOM_CREATE_TIMEOUT); while (_lbClient.State != ClientState.JoinedLobby && t.Waiting) { yield return(null); } if (_lbClient.State != ClientState.Joined) { BoltLog.Warn("Can't call BoltNetwork.UpdateHostInfo while not in a room"); yield break; } //var maxPlayers = dedicated ? BoltNetwork.maxConnections : BoltNetwork.maxConnections + 1; var customRoomProperties = default(ExitGames.Client.Photon.Hashtable); // check for old host info token var hostInfoToken = protocolToken as PhotonHostInfoToken; if (hostInfoToken != null) { customRoomProperties = hostInfoToken.CustomRoomProperties; } // check for new interface based version var boltPhotonCloudRoomProperties = protocolToken as IBoltPhotonCloudRoomProperties; if (boltPhotonCloudRoomProperties != null) { customRoomProperties = boltPhotonCloudRoomProperties.CustomRoomProperties; } // last resort, create a new empty table if (customRoomProperties == null) { customRoomProperties = new ExitGames.Client.Photon.Hashtable(); } // if we have a protocol token, and it's not PhotonHostInfoToken package it into the room properties as Byte[] if (protocolToken != null && !(protocolToken is PhotonHostInfoToken)) { customRoomProperties["UserToken"] = ProtocolTokenUtils.ToByteArray((IProtocolToken)protocolToken); } // session id //customRoomProperties["UdpSessionId"] = Guid.NewGuid().ToString(); // if we allow punch //if(_config.UsePunchThrough) { // customRoomProperties["SocketPeerId"] = BoltNetwork.UdpSocket.SocketPeerId.ToString(); //} // _lbClient.OpSetCustomPropertiesOfRoom(customRoomProperties); BoltConsole.Write("Updating room properties"); }
private void OnHealthChanged() { // Dead if (entity.IsOwner && state.Health <= 0) { BoltLog.Warn("Player is dead: {0}", entity.NetworkId); StartCoroutine(RespawnRoutine()); } }
public override void SessionConnectFailed(UdpSession session, IProtocolToken token) { var photonSession = session as PhotonSession; string sessionDescription = String.Format("{0} / {1} ({2})", photonSession.Source, photonSession.HostName, photonSession.Id); BoltLog.Warn("Failed to Connect to: {0}", sessionDescription); }
// BOLT public override void BoltShutdownBegin(AddCallback registerDoneCallback) { SceneManager.LoadScene("Menu"); registerDoneCallback(() => { BoltLog.Warn("Bolt is down"); }); }
public override void Connected(BoltConnection connection) { BoltLog.Warn("Connected"); connection.UserData = new Player(); connection.GetPlayer().connection = connection; connection.GetPlayer().name = "CLIENT:" + connection.RemoteEndPoint.Port; connection.SetStreamBandwidth(1024 * 1024); }
void Start() { #if UNITY_EDITOR_OSX Process p = new Process(); p.StartInfo.FileName = "osascript"; p.StartInfo.Arguments = @"-e 'tell application """ + UnityEditor.PlayerSettings.productName + @""" activate end tell'"; p.Start(); #endif BoltRuntimeSettings settings = BoltRuntimeSettings.instance; _serverEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, (ushort)settings.debugStartPort); _clientEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, 0); BoltConfig cfg; cfg = settings.GetConfigCopy(); cfg.connectionTimeout = 60000000; cfg.connectionRequestTimeout = 500; cfg.connectionRequestAttempts = 1000; if (string.IsNullOrEmpty(settings.debugStartMapName) == false) { if (BoltDebugStartSettings.DebugStartIsServer) { BoltLog.Warn("Starting as SERVER"); BoltLauncher.StartServer(_serverEndPoint, cfg); } else if (BoltDebugStartSettings.DebugStartIsClient) { BoltLog.Warn("Starting as CLIENT"); BoltLauncher.StartClient(_clientEndPoint, cfg); } else if (BoltDebugStartSettings.DebugStartIsSinglePlayer) { BoltLog.Warn("Starting as SINGLE PLAYER"); BoltLauncher.StartSinglePlayer(cfg); } BoltDebugStartSettings.PositionWindow(); } else { BoltLog.Error("No map found to start from"); } }
public override void ConnectRequest(UdpKit.UdpEndPoint endpoint, Bolt.IProtocolToken token) { BoltLog.Warn("ConnectRequest"); if (token != null) { BoltLog.Info("Token Received"); } BoltNetwork.Accept(endpoint); }
private IEnumerator RespawnRoutine() { if (entity.IsOwner && state.Health <= 0) { yield return(new WaitForSeconds(3)); SetState(SpawnPointsManager.GetSpawnPosition(), Vector3.zero, 0); state.Health = 100; BoltLog.Warn("Player respawn: {0}", entity.NetworkId); } }
public void StartCountDown() // triggered by pressing J { if (EventManager.Instance.Connections < MaxPlayersToStart) { BoltLog.Warn("There are not enough players to start the game!"); return; } Game_Counter_Started = true; var evnt = StartLobbyCounter.Create(); evnt.Message = "Starting the game..."; evnt.Send(); }
public static void RemovePlayer(uint playerId) { if (PlayerList.ContainsKey(playerId)) { BagManager.RemovePlayerBag(Convert.ToInt32(playerId)); BoltNetwork.Destroy(PlayerList[playerId]); PlayerList.Remove(playerId); } else { BoltLog.Warn($"try to remove not existed player with connection id {playerId}"); } }
public static List <ItemInfo> DecodeBag(string encode) { BoltLog.Warn($"encode string length:{encode.Length}"); var ret = new List <ItemInfo>(); for (var i = 0; i < encode.Length; i += 2) { ret.Add(new ItemInfo(Convert.ToInt32(encode[i]), Convert.ToInt32(encode[i + 1]))); } return(ret); }
public override void BoltStartDone() { BoltLog.Warn("set loading MainGame Scene~~"); if (BoltNetwork.IsClient) { return; } var matchName = Guid.NewGuid().ToString(); BoltMatchmaking.CreateSession( matchName, sceneToLoad: "MainGame" ); }
/// <summary> /// Runs only on the Server, just so signal that a remote client has loaded scene /// </summary> public override void OnEvent(LoadSceneResponse evnt) { if (BoltNetwork.IsServer) { if (evnt.Load) { BoltLog.Warn("Connection {0} has loaded scene {1}", evnt.RaisedBy, evnt.SceneName); } else { BoltLog.Warn("Connection {0} has unloaded scene {1}", evnt.RaisedBy, evnt.SceneName); } } }
void State_SelectRoom() { GUI.Label(labelRoom, string.Format("Looking for rooms ({0}):", 5000 - watch.ElapsedMilliseconds), labelRoomStyle); if (BoltNetwork.SessionList.Count > 0) { if (watch.IsRunning == false) { BoltLog.Warn("Start connect timer"); autoConnect = false; watch.Start(); } if (watch.ElapsedMilliseconds > 5000) { autoConnect = true; } GUILayout.BeginVertical(); GUILayout.Space(30); foreach (var session in BoltNetwork.SessionList) { var photonSession = session.Value as PhotonSession; if (photonSession.Source == UdpSessionSource.Photon) { var matchName = photonSession.HostName; var label = string.Format("Join: {0} | {1}/{2} | {3}", matchName, photonSession.ConnectionsCurrent, photonSession.ConnectionsMax, photonSession.IsOpen ? "Open" : "Closed"); if ((ExpandButton(label) || autoConnect) && photonSession.IsOpen) { BoltNetwork.Connect(photonSession); autoConnect = false; watch.Stop(); watch.Reset(); } } } GUILayout.EndVertical(); } else { watch.Stop(); watch.Reset(); } }
/// <summary> /// When a new client connects after the game was already started, this makes sure that it will /// load all already loaded additive scenes. /// </summary> public override void SceneLoadRemoteDone(BoltConnection connection, IProtocolToken token) { if (BoltNetwork.IsServer) { BoltLog.Warn("Remote Connection {0} has Loaded Scene", connection); foreach (var item in loadedScenes) { var evt = LoadSceneRequest.Create(connection, ReliabilityModes.ReliableOrdered); evt.SceneName = item; evt.Load = true; evt.Send(); } } }
private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input. private void Start() { // get the transform of the main camera if (Camera.main != null) { m_Cam = Camera.main.transform; } else { BoltLog.Warn("Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls."); // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them! } // get the third person character ( this should never be null due to require component ) m_Character = GetComponent <ThirdPersonCharacter>(); }
private static List <STuple <BoltGlobalBehaviourAttribute, Type> > GetGlobalBehaviourTypes() { var globalBehaviours = new List <STuple <BoltGlobalBehaviourAttribute, Type> >(); var asmIter = BoltAssemblies.AllAssemblies; var assemblyList = AppDomain.CurrentDomain.GetAssemblies(); while (asmIter.MoveNext()) { try { // Load Assembly var asm = Array.Find(assemblyList, (assembly) => assembly.GetName().Name.Equals(asmIter.Current)); // Skip of not found if (asm == null) { continue; } foreach (Type type in asm.GetTypes()) { try { if (typeof(MonoBehaviour).IsAssignableFrom(type)) { var globalAttr = type.GetCustomAttribute <BoltGlobalBehaviourAttribute>(false); if (globalAttr != null) { globalBehaviours.Add(new STuple <BoltGlobalBehaviourAttribute, Type>(globalAttr, type)); } } } catch (Exception e2) { BoltLog.Warn(e2); } } } catch (Exception e) { BoltLog.Warn(e); } } return(globalBehaviours); }
public override void SessionListUpdated(Map <Guid, UdpSession> sessionList) { BoltLog.Warn("{0} :: Session list updated: {1} total sessions", Time.frameCount, sessionList.Count); // BoltLog.Warn("{0} :: Session list updated: {1} total sessions", Time.frameCount, sessionList.Count); Debug.LogFormat("{0} :: Session list updated: {1} total sessions", Time.frameCount, sessionList.Count); // foreach (var session in sessionList) // { // UdpSession udpSession = session.Value as UdpSession; // PhotonSession photonSession = udpSession as PhotonSession; // if (photonSession.Source == UdpSessionSource.Photon) // { // // BoltNetwork.Connect(photonSession); // } // } }
public override void OnEvent(SimpleButtonBoltEvent evnt) { BoltLog.Warn($"{this} evt received | {evnt}"); if (evnt.ParentId != _parentId || evnt.Id != _id) { return; } if (_isWaitingLockStateDelay) { return; } StartCoroutine(LockDelayRoutine()); onEventReceived?.Invoke(); }
public void OnHurt(int dmg) { BoltLog.Warn($"player {playerId} get hurt for {dmg}"); health -= dmg; var dmgEvent = OnDamaged.Create(entity, EntityTargets.OnlyController); dmgEvent.TargetID = Convert.ToInt32(playerId); dmgEvent.Dmg = dmg; dmgEvent.Send(); if (health > 0) { return; } OnPlayerDeath.Post(GlobalTargets.AllClients, playerId); PlayerRegistry.RemovePlayer(Convert.ToUInt32(playerId)); }