You can cache some vector math here

Similar to a previous lecture, you can use the caching technique to reduce the amount of calculations you are doing per frame.

[SerializeField] float thrust = 1000f;
Vector3 thrustVector;

void Start()
{
  // Other code.
   thrustVector = Vector3.up * thrust;
}

void Update()
{
    // Other code.
    rb.AddRelativeForce(thrustVector * Time.deltaTime);
}

Since (right now) thrust is not variable don’t need to multiply the Vector3.up by it each frame.

You could do your math outside of the update function to save a marginal amount of execution time on the multiplication each frame. But modern day processors are actually quite fast and efficient at multiplication even on mobile devices. And I am not sure that creating the extra variable which would use 24 bytes of memory would be worth the performance gain in this case.

umm… no.

Usually I’d leave this alone since it’s a necro thread but it speaks to what I was mentioning in the other thread.

Assuming there’s no mistake (which I think is a mistake, but that’s another topic) to adding the thrustVector * Time.deltaTime. The worrying of the performance hit in both processor units and garbage controller can be dangerous.

Before worrying about performance issues, it’s important for a programmer to get a wide knowledge base and when they get a wider base, not blindside themselves with a narrow focus.

Time.deltaTime. It’s a variable that measures the time between Update() ticks. In this case, if you try to cache the variable or any result of any calculation derived from it, you’re likely (not guaranteed) to end up with incorrect calculations or unpredictable/unexpected results.

On a side point, how are you going in your Unity course(s)? It sounds like you’ve done a bit of a programming? What have you coded in?

Hi Michael, I’m very confused.

Time.deltaTime isn’t being cached in my example. It’s being used in the Update method directly, whenever it’s needed. I understand that it will return different numbers so caching it needs to be done with care.

The math that I’ve cached here is just the Vector3.up * thrust calculation. There was no way for us to affect thrust during play so this made sense to me.

Sorry Dave, that was for IceDragon. I must have cliced on the wrong reply. I also didn’t expect you to reply.

And you are right. Caching those kinds of variables is a good way to do it.

Privacy & Terms