0
\$\begingroup\$

I'm developing a simple 2D game in Unity (balls hitting bricks), so I have a ball and I want to fire the ball to hit bricks. Now, to fire the ball I have to set velocity on the Rigidbody component attached to the ball's GameObject.

There are two ways to do that:

Method 1:

Set the velocity inside the Start() method

private void Start()
{
    rb.velocity = direction * speed;
}

Method 2:

Write a FixedUpdate() method and put the statement in there. because:

Use FixedUpdate when using Rigidbody. (Unity Docs)

private void Start()
{
    _setVelocity = true;
}

private void FixedUpdate()
{
    if (!_setVelocity) return;

    rb.velocity = direction * speed;
    rb.angularVelocity = 0;
    rb.gravityScale = 0;
    _setVelocity = false;
}

But the thing is: I don't need the FixedUpdate() method for anything else, because I only fire the ball once in its script's lifespan, so after I fire the ball Unity will continue to run the FixedUpdate() method and check for _setVelocity's value and return (exit) every time because it will always be false after I shoot the ball the first time.

And this will happen every fixed time step which is expensive I guess for just setting the velocity only once.

SO:

  1. Is it expensive to have a FixedUpdate() method that checks for false value and returns every frame?
  2. Which of the two methods performs better in this case?
\$\endgroup\$
2
  • \$\begingroup\$ It sounds like you have your answer "I don't need the FixedUpdate() method...because I only fire the ball once in its script's lifespan". For a question about expense/performance, I'd usually say "profile it to find out for yourself" but in this case you don't need to: you know not calling a method every physics step is cheaper than calling it, so you don't even need to ask this question. \$\endgroup\$
    – DMGregory
    Jun 8, 2020 at 22:18
  • \$\begingroup\$ I know but Unity said in their Docs to always use FixedUpdate() when dealing with RigidBodies. So that's why i'm asking. Unity Docs \$\endgroup\$
    – Fadi Obaji
    Jun 8, 2020 at 22:20

1 Answer 1

1
\$\begingroup\$

"Put physics effects in FixedUpdate" is talking about ongoing effects, not initial setup.

So really, it could be better phrased as "Use FixedUpdate instead of Update for ongoing physics effects"

Just put the initial velocity assignment in Start. Test your game. Observe that nothing bad happens.

Note that this caveat also means it's OK to put instantaneous effects - like responding to a jump button being pressed - in Update. It won't have an impact on the integrated position of the object until the next physics step (unless you're using extrapolation), but that's no worse than queuing-up the input and handling it in the next FixedUpdate anyway.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .