When you modify rigidbody.velocity, you can’t modify the x/y/z one at a time, you have to assign the whole thing at once using a vector.
The reason for this is a bit subtle. It looks like rigidbody.velocity is a variable, but it’s actually a property. Properties look like variables but are actually functions (one function for getting the value, and another function for setting the value). Behind the scenes, the compiler is replacing rigidbody.velocity = myVector;
with something like rigidbody.SetVelocityTo(myVector);
The reason is even more subtle. Would velocity be regular class, your code would work just fine. But velocity is Vector3, wich is value type. Value types are always copied. So when you write
var velocity = body.velocity;
actually happens
call to property get function
create copy of Rigidbody’s private velocity variable
put that copy into local variable of calling function
sou your code modifies values x,y of a copy of rigidbody valocity, but you have not create local vairable to it so your modification will be lost. that’s why this is error rewrite:
This is how it is intended to work. This code creates local variable, accepts a copy of rigidbody private velocity class field, modifies it, and writes back the modified value.