- Home /
Set RigidBody velocity in FixedUpdate() or Start()?
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 frame-rate frame 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?
Answer by FlaSh-G · Jun 09, 2020 at 09:43 AM
Definitely not. Unless you have hundreds of thousands of objects doing a thing, don't stress about s simple thing like this. It might be of interest to note though that you can have the same effect by just setting1 Is it expensive to have a FixedUpdate() method that checks for false value and returns every frame?
enabled
to
false
, as
FixedUpdate
is only called on enabled Behaviours.
There is no answer to this questions because they both do different things. Only setting in2 Which of the two methods performs better in this case?
Start
allows influences in later points in time to change the velocity again, whereas setting it in FixedUpdate makes the object stay on course. The
Start
variant does less work, but the numbers are so small that it doesn't matter at all.
Yes but there are times that the player can shoot 200 balls, and maybe more
The golden rule of optimization: Try it and improve it if it's too slow.
Your answer
Follow this Question
Related Questions
Can the Script Execution order be adjusted for FixedUpdate()? 3 Answers
rigidbody2D velocity zero? 1 Answer
MovePosition with Multiple Scripts 1 Answer
My character won't stop jumping!!! 1 Answer