Round Timer for Player Turns

Hello again guys,

So I've been developing a kind of turn based game where two players are across a field and they need to shoot each other with catapults. I need the players to be able to shoot only once in each round. A round is 40 seconds, and then I need to disable one players controls over the network and enable the opponents components and start his round and so on. Kind of like Worms Armageddon.

So far I've tried implementing the timer in a object that's part of the scene and not of the player, and the timer starts when both players are connected. The things is that the timer works only on the player that connects second, on the first one nothing is happening. Do I need to send the timer via RPC or how ?

This is my code:
public class TimerScript : MonoBehaviour {
 
	//public vars
	public bool timerStart;
	public int values;
	
	//private vars
	private EnergyBar timerValue;
	private float startTime;
	
	public GameObject[] players;
	private bool boolVal;
	// Use this for initialization
	void Start () {
		timerValue=GetComponent<EnergyBar>();
		startTime=Time.time;
		boolVal=true;
	}
	
	// Update is called once per frame
	void Update () {
		print(PhotonNetwork.countOfPlayers);
		if(PhotonNetwork.countOfPlayers == 2){   
		   timerStart=true;
		}else{
		   timerStart=false;
		}
		
		if(timerStart){
			SwitchPlayer();
			StartTimer();
		}		
	}
	
	void StartTimer(){
		float timeStep = Time.time - startTime;
		float seconds = timeStep % 60;
		values = (int)seconds;
		timerValue.valueCurrent = values; // this sends the value to my GUI Timer Prefab
		
		if(values == 41){
			//timerStart=false;
			ResetTimer();
		}
	}
	
	void ResetTimer(){
		startTime=Time.time;
		values=0;
		timerValue.valueCurrent = values; // this sends the value to my GUI Timer Prefab
		timerStart=true;
	}
	
	void SwitchPlayer(){
	      //pass controls to opponent
	}
}

Comments

  • You can start the timer when the second player joins.
    You could implement OnPhotonPlayerConnected(PhotonPlayer newPlayer) which is called on existing players when a new one joins. Also implement OnJoinedRoom() which is called on each client when it enters a room. If you check in both methods if enough players are available, you can easily start the timer at about the same time and don't need to sync a timer.
    Alternatively, your Master Client can send and RPC to start a timer or you can set a room property to have a synced time.

    As you can shortcut the timer by doing your single action, I would probably send an RPC "my round started at X" where X is a parameter containing the PhotonNetwork.time, which is synced per room. This way, the other client knows pretty exactly when your turn started and when it ends.