This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| using UnityEngine.Networking; | |
| public class CustomNetworkManager : NetworkManager | |
| { | |
| #region Server side | |
| public override void OnStartServer () | |
| { | |
| base.OnStartServer(); | |
| // we're the Server, dont need to sync with anyone :) | |
| _isSyncTimeWithServer = true; | |
| syncServerTime = Network.time; | |
| } | |
| /// <summary> | |
| /// On server, be called when a client connected to Server | |
| /// </summary> | |
| public override void OnServerConnect (NetworkConnection conn) | |
| { | |
| base.OnServerConnect(conn); | |
| Debug.Log("---- Server send syncTime to client : " + conn.connectionId); | |
| var syncTimeMessage = new SyncTimeMessage(); | |
| syncTimeMessage.timeStamp = Network.time; | |
| NetworkServer.SendToClient(conn.connectionId, CustomMsgType.SyncTime, syncTimeMessage); | |
| } | |
| #endregion | |
| #region Client side | |
| public override void OnStartClient (NetworkClient client) | |
| { | |
| base.OnStartClient(client); | |
| client.RegisterHandler(CustomMsgType.SyncTime, OnReceiveSyncTime); | |
| } | |
| void OnReceiveSyncTime(NetworkMessage msg) | |
| { | |
| var castMsg = msg.ReadMessage<SyncTimeMessage>(); | |
| _isSyncTimeWithServer = true; | |
| syncServerTime = castMsg.timeStamp; | |
| Debug.Log("--------Client receive : " + syncServerTime); | |
| } | |
| #endregion | |
| #region Update sync time | |
| /// <summary> | |
| /// Use this, instead of Network.time . Sure this var will be | |
| /// sync on both Server and all connected clients | |
| /// </summary> | |
| public static double syncServerTime; | |
| /// Do we receive the syncTime from Server ? | |
| bool _isSyncTimeWithServer = false; | |
| void Update() | |
| { | |
| if (_isSyncTimeWithServer) | |
| { | |
| syncServerTime += Time.deltaTime; | |
| // This Log just to show the syncTime to console for testing purpose | |
| // remove it in your project | |
| Debug.Log("SyncTime : " + syncServerTime); | |
| } | |
| } | |
| #endregion | |
| } | |
| #region Custom classes | |
| public class CustomMsgType | |
| { | |
| public const short SyncTime = MsgType.Highest + 1; | |
| } | |
| public class SyncTimeMessage : MessageBase | |
| { | |
| public double timeStamp; | |
| } | |
| #endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment