Hello all! I made simple Timer script but I want use it in my multiplayer FPS game. So I need synchronizate Timer to all players see same time. Can you please help me? There is my Timer script:
`using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public int timeLeft = 5;
public Text countdownText;
// Use this for initialization
void Start()
{
StartCoroutine("LoseTime");
}
// Update is called once per frame
void Update()
{
countdownText.text = ("Time Left = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine("LoseTime");
countdownText.text = "Times Up!";
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds(1);
timeLeft--;
}
}
you can use PhotonNetwork.time to create a synchronized timer. When the game begins you can add this value as a Custom Room Property and let each client calculate the timer on their own. Therefore the MasterClient can set this value by using the following code - or similar:
Hashtable ht = new Hashtable {{"StartTime", PhotonNetwork.time}};
PhotonNetwork.room.SetCustomProperties(ht);
You now have to implement a callback called OnPhotonCustomRoomPropertiesChanged. This might look like the following:
public void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged)
{
object propsTime;
if (propertiesThatChanged.TryGetValue("StartTime", out propsTime))
{
startTime = (double) propsTime;
}
}
The variable ‘startTime’ is a local variable in my example, ‘gameStarted’ is a bool that describes what its name says - obviously. Having this value each client can calculate a timer on their own by using the following:
public void Update()
{
if (!gameStarted)
{
return;
}
// Example for a increasing timer
incTimer = PhotonNetwork.time - startTime;
// Example for a decreasing timer
double roundTime = 300.0;
decTimer = roundTime - incTimer;
}
my Timer script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public int timeLeft = 5;
public Text countdownText;
// Use this for initialization
void Start()
{
StartCoroutine("LoseTime");
}
// Update is called once per frame
void Update()
{
countdownText.text = ("Time Left = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine("LoseTime");
countdownText.text = "Times Up!";
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds(1);
timeLeft--;
}
}