Search Unity

Using Time.time in an if statement?

Discussion in 'Scripting' started by CosmoKing, Aug 19, 2009.

  1. CosmoKing

    CosmoKing

    Joined:
    Feb 23, 2009
    Posts:
    111
    I'm trying to use the following code to wait for two and a half seconds before playing an audio clip attached to the same GameObject:

    Code (csharp):
    1. function Update() {
    2.     var PlayTime = 2.5;
    3.     if (Time.time = PlayTime) {
    4.         audio.Play();
    5.     }
    6. }
    I get the following error:
    (3, 23) BCE0044 expecting ) found '='
    Fixing this error (changing it to (Time.time) = PlayTime )causes another error:
    (3, 24) BCE0043 unexpected token =

    Any idea what is wrong? I know I saw Time.time used in a similar way in a scripting reference example.
     
  2. Discord

    Discord

    Joined:
    Mar 19, 2009
    Posts:
    1,008
    Code (csharp):
    1. if (Time.time = PlayTime) {
    should be
    Code (csharp):
    1. if (Time.time == PlayTime) {
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That won't work anyway, since Time.time will almost certainly never equal exactly 2.5. Don't use Update at all, use yield WaitForSeconds in Start.

    --Eric
     
  4. Murcho

    Murcho

    Joined:
    Mar 2, 2009
    Posts:
    309
    I'd suggest the coroutine route as well, however if you don't feel confident enough to travel down that path yet, you should alter your if test to:
    Code (csharp):
    1.  
    2. if (Time.time >= PlayTime)
    3. {
    4.    audio.Play();
    5. }
    You need to be careful though as this will continue to call the play function after this, so using a coroutine with WaitForSeconds will probably be the safer route to go.