So, this is kind of an odd situation; I have two scripts attached to a rigidbody. One script will apply a horizontal force when the player presses a button:
// Apply a force in a direction.
rigidbody.AddForce(dir * power, ForceMode.Impulse);
And another has logic for limiting the velocity of the rigidbody:
Vector3 tempVelocity = rigidbody.velocity;
if(maxVelocitySq > 0.0f && tempVelocity.sqrMagnitude > maxVelocitySq)
{
tempVelocity *= slowdownRate;
}
rigidbody.velocity = tempVelocity;
However, when I run the game, the horizontal force doesn’t work. I thought that there might be some sort of conflict or overwriting of the rigidbody’s velocity force based on the update order of these two scripts, but then I found that I could fix the problem by NOT using a temporary variable in the second script:
// If velocity is too high, apply a slowdown.
if(maxVelocitySq > 0.0f && rigidbody.velocity.sqrMagnitude > maxVelocitySq)
{
rigidbody.velocity *= slowdownRate;
}
And that second version works fine.
My question, then: why would using a temporary variable break the AddForce line in the first script? Does Unity execute physics updates concurrently on different threads, so using a temp variable might overwrite some data? Is there something wrong with using a temp variable? Or is it a bug that rigidbodies would behave this way? I’d note that I’m working on an iOS/Android title, but I only ever see this behavior in the editor.