Skip to content

Instantly share code, notes, and snippets.

@ThinhHB
Last active February 13, 2020 14:58
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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