Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to do some action exaclty X times per second?

Discussion in 'Scripting' started by Pavelyev, Mar 26, 2015.

  1. Pavelyev

    Pavelyev

    Joined:
    Mar 25, 2015
    Posts:
    4
    Hello!

    I'm looking survival shooter project. There is code which I consider doubtful.
    Code (CSharp):
    1.     public float timeBetweenAttacks = 0.5f;
    2.     void Update ()
    3.     {
    4.         timer += Time.deltaTime;
    5.  
    6.         if(timer >= timeBetweenAttacks && playerInRange)
    7.         {
    8.             Attack ();
    9.         }
    10.  
    11.         if(playerHealth.currentHealth <= 0)
    12.         {
    13.             anim.SetTrigger ("PlayerDead");
    14.         }
    15.     }
    As I have understand the Update function may be called different times per second. So we can't assert that enemy hits player 2 times per second with condifence.
     
  2. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    what you got should work, yes it will be small fractions of a second off, but consider that the update is firing prolly 60 times a second or more it will be close enough
     
  3. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    Assuming you don't have serious framerate issues, that code works just fine. At worst you will be about 0.03 seconds off track, assuming you are dipping to 30FPS.

    When you reset your timer (on attack, I assume), just subtract timeBetweenAttacks rather than resetting to 0. That way if your previous attack was just barely late, your next attack should arrive a bit quicker to compensate and keep you on track.

    There are other techiniques, like coroutines or invoke repeating, that you can use as well, but I don't think that your current method will have anywhere near the impact you fear it will.