Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by JJNCreator · Jan 12, 2015 at 03:11 PM · c#networkingmultiplayerphotontimer

Photon timer issue

I'm working on a multiplayer game, and I'm using Photon+ for the networking. I have a modified version of the InRoomRoundTimer script. I'm trying to have it tell a Boolean value to set to true. But instead, the timer resets and the value isn't called. How can I fix this? Thanks for the help!

Here's the code:

 using UnityEngine;
 using ExitGames.Client.Photon;
 
 public class MatchTimer : MonoBehaviour {
     public int SecondsPerMatch = 5;                  // time per round/turn
     public double StartTime;                        // this should could also be a private. i just like to see this in inspector
     public Rect TextPos = new Rect(0, 80, 150, 300);   // default gui position. inspector overrides this!
     public double timeRemaining = 20;
 
     private bool startRoundWhenTimeIsSynced;        // used in an edge-case when we wanted to set a start time but don't know it yet.
     private const string StartTimeKey = "st";       // the name of our "start time" custom property.
     public bool showResults = false;
 
 
     private void StartRoundNow()
     {
         // in some cases, when you enter a room, the server time is not available immediately.
         // time should be 0.0f but to make sure we detect it correctly, check for a very low value.
         if (PhotonNetwork.time < 0.0001f)
         {
             // we can only start the round when the time is available. let's check that in Update()
             startRoundWhenTimeIsSynced = true;
             showResults = true;
             return;
         }
         startRoundWhenTimeIsSynced = false;
         showResults = false;
 
 
 
         ExitGames.Client.Photon.Hashtable startTimeProp = new Hashtable();  // only use ExitGames.Client.Photon.Hashtable for Photon
      //   startTimeProp[StartTimeKey] = PhotonNetwork.time;
      //   PhotonNetwork.room.SetCustomProperties(startTimeProp);              // implement OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged) to get this change everywhere
     }
 
 
     /// <summary>Called by PUN when this client entered a room (no matter if joined or created).</summary>
     public void OnJoinedRoom()
     {
         if (PhotonNetwork.isMasterClient)
         {
         //    this.StartRoundNow();
             showResults = false;
         }
         else
         {
             // as the creator of the room sets the start time after entering the room, we may enter a room that has no timer started yet
             Debug.Log("StartTime already set: " + PhotonNetwork.room.customProperties.ContainsKey(StartTimeKey));
         }
     }
     void Start()
     {
     //    StartRoundNow();
     //    showResults = true;
     }
 
     /// <summary>Called by PUN when new properties for the room were set (by any client in the room).</summary>
     public void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged)
     {
         if (propertiesThatChanged.ContainsKey(StartTimeKey))
         {
             //StartTime = (double)propertiesThatChanged[StartTimeKey];
             //showResults = true;
         }
     }
 
     /// <remarks>
     /// In theory, the client which created the room might crash/close before it sets the start time.
     /// Just to make extremely sure this never happens, a new masterClient will check if it has to
     /// start a new round.
     /// </remarks>
     public void OnMasterClientSwitched(PhotonPlayer newMasterClient)
     {
         if (!PhotonNetwork.room.customProperties.ContainsKey(StartTimeKey))
         {
             Debug.Log("The new master starts a new round, cause we didn't start yet.");
          //   this.StartRoundNow();
         }
     }
 
 
     void Update()
     {
         if (startRoundWhenTimeIsSynced)
         {
         //    showResults = true;
          //   this.StartRoundNow();   // the "time is known" check is done inside the method.
         }
         if (timeRemaining <= 0.0001f)
         {
             timeRemaining = 0;
             showResults = true;
         }
       /*  if (PhotonNetwork.time < 0.0001f)
         {
             showResults = true;
         }*/
     }
 
     public void OnGUI()
     {
         // alternatively to doing this calculation here:
         // calculate these values in Update() and make them publicly available to all other scripts
         double elapsedTime = (PhotonNetwork.time - StartTime);
         double remainingTime = SecondsPerMatch - (elapsedTime % SecondsPerMatch);
       //  int turn = (int)(elapsedTime / SecondsPerMatch);
 
         timeRemaining = remainingTime;
 
 
         // simple gui for output
         GUILayout.BeginArea(new Rect(Screen.width - 570, 0, 200, 40));
     //    GUILayout.Label(string.Format("elapsed: {0:0.000}", elapsedTime));
         GUILayout.Box(string.Format("Time remaining: {0:0}", remainingTime));
      //   GUILayout.Label(string.Format("turn: {0:0}", turn));
    /*     if (GUILayout.Button("new round"))
         {
             this.StartRoundNow();
         }*/
         GUILayout.EndArea();
 
         if (timeRemaining <= 0.0001f)
             showResults = true;
 
         if (showResults)
         {
             ShowResults();
         }
     }
     void ShowResults()
     {
         GUILayout.BeginArea(new Rect((Screen.width - 400) / 2, (Screen.height - 300) / 2, 400, 300));
         GUILayout.Label("Match results:");
         foreach (PhotonPlayer pl in PhotonNetwork.playerList)
         {
             GUILayout.BeginHorizontal();
             GUILayout.Label("Name: " + pl.name);
             GUILayout.Label("Kills: " + pl.GetScore());
             GUILayout.Label("Team: " + pl.GetTeam());
             GUILayout.EndHorizontal();
         }
         GUILayout.Label("After seeing your score, you may leave and return to the lobby");
         GUILayout.EndArea();
     }
 }
Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tobiass · Jan 12, 2015 at 04:41 PM 0
Share

We can't see your modification, so it's hard to help. You want to set one bool value after a specified time? When does the timer start?

avatar image UnSpotibleShadow · Jan 12, 2015 at 05:42 PM 0
Share

Some code would be appreciated

avatar image JJNCreator · Jan 12, 2015 at 09:43 PM 0
Share

I edited the post and added some code. Right now, I have the timer set to 20 seconds, but in the final build, I'm going to set it to 180 seconds.

avatar image JJNCreator · Jan 13, 2015 at 09:17 PM 0
Share

Any luck, @tobiass?

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by tobiass · Jan 14, 2015 at 11:34 AM

I don't know exactly what you want to achieve but if you want a bool to be true after a certain time in a room, then why don't you just store a property when this happens? It's current time + duration.

All clients can check if it's later than the time you stored.

I skipped most of the GUI stuff but this is how I'd do it.

 using System.IO;
 using ExitGames.Client.Photon;
 using Photon;
 using UnityEngine;
 
 public class MatchTimer : PunBehaviour
 {
     private const string TimeToStartProp = "st";
     private double timeToStart = 0.0f;
     public double SecondsBeforeStart = 20.0f;   // set in inspector
 
     public bool IsItTimeYet
     {
         get { return IsTimeToStartKnown && PhotonNetwork.time > this.timeToStart; }
     }
 
     public bool IsTimeToStartKnown
     {
         get { return this.timeToStart > 0.001f; }
     }
 
     public double SecondsUntilItsTime
     {
         get
         {
             if (this.IsTimeToStartKnown)
             {
                 double delta = this.timeToStart - PhotonNetwork.time;
                 return (delta > 0.0f) ? delta : 0.0f;
             }
             else
             {
                 return 0.0f;
             }
         }
     }
 
     void Update()
     {
         if (PhotonNetwork.isMasterClient)
         {
             // the master client checks if a start time is set. we check a min value
             if (!this.IsTimeToStartKnown && PhotonNetwork.time > 0.0001f)
             {
                 // no startTime set for room. calculate and set it as property of this room
                 this.timeToStart = PhotonNetwork.time + SecondsBeforeStart;
 
                 Hashtable timeProps = new Hashtable() {{TimeToStartProp, this.timeToStart}};
                 PhotonNetwork.room.SetCustomProperties(timeProps);
             }
         }
     }
 
     public override void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged)
     {
         if (propertiesThatChanged.ContainsKey(TimeToStartProp))
         {
             this.timeToStart = (double) propertiesThatChanged[TimeToStartProp];
             Debug.Log("Got StartTime: " + this.timeToStart + " is it time yet?! " + this.IsItTimeYet);
         }
     }
 
     void OnGUI()
     {
         GUILayout.Label("Is it time yet: " + this.IsItTimeYet);
         GUILayout.Label("Seconds until it's time: " + (float)this.SecondsUntilItsTime);
     }
 }
Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image JJNCreator · Jan 14, 2015 at 12:43 PM 0
Share

Thanks. I'll try it :)

avatar image JJNCreator · Jan 14, 2015 at 07:30 PM 0
Share

It works! Awesome! Thanks

avatar image JJNCreator · Jan 14, 2015 at 08:34 PM 0
Share

I just have one more question. How do you sync the time over the network? When someone joins your room, their time is stays at 0 until the mc leaves. How do I fix this?

avatar image tobiass · Jan 15, 2015 at 09:03 AM 0
Share

The code above does sync it over the network. The room properties are synced. When someone joins, that client should call OnPhotonCustomRoomPropertiesChanged and set timeToStart immediately. Afaik, it does this.

avatar image JJNCreator · Jan 15, 2015 at 04:36 PM 0
Share

Thanks. I'll take a look at this.

avatar image
0

Answer by juraj123 · Aug 03, 2018 at 01:38 PM

Sorry for re-opening this, but when I want to some object be SetActive when time is 0, how to do this? I used this script above from @tobiass

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

28 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Updating multiplayer map on joining 1 Answer

Unity networking tutorial? 6 Answers

[Photon] Looking for example code for late joining clients syncing instantiated game objects that don't exist in the base scene 0 Answers

Photon Cloud, Multiplayer Damage script 0 Answers

Networking - Move all players to a position? (Photon) 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges