Search Unity

Question Time.deltaTime retrieval centralized or distributed on different components

Discussion in 'Scripting' started by dichtermut, Apr 22, 2023.

  1. dichtermut

    dichtermut

    Joined:
    Jul 21, 2018
    Posts:
    26
    I started by having a Time.deltaTime in the Update() method of a Shooting component, which is used by different game objects that shoot projectiles, to know when it's time to shoot again.
    Then I added another Time.deltaTime to the Update() method of the Combat component, which is similar to Shooting, but tracks the melee attacks.
    As I try to keep my different functionalities as modular as possible, I have been adding lots of components, quite a few of them using Time.deltaTime. So my question is: is having several Time.deltaTime across different components considered a good practice? I suppose that the cost is negligible, I'm referring to the design decision of it.
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    From a design perspective, why would you repeat yourself constantly, or access the Time class all the time? Save it to local deltaTime, use
    deltaTime
    everywhere. You also get to rename it to
    dt
    , which will make your code super-compact and easy to read.

    You're right, the difference in performance should be negligible, but it pays off aesthetically. You can also cascade it down as an argument, make all of your subsequent methods as pure as possible.