How to set velocity on a single axis only?

I know we can set velocity by using

rigidbody.velocity = new Vector3(hori * 5, ver * 5, 0);

But how do I set the velocity of a single axis? I tried

rigidbody.velocity.x = 5f;

But it’s a return type and doesn’t work.

Any help?

Copy the value of velocity to a vector of your own, set the x component to 5, then copy it back. Something like this:

Vector3	v = rigidbody.velocity;
v.x = 5.0f;
rigidbody.velocity = v;

Other options mess up the gravity, at least in 2d.

amazing solution:

yVel = rb2d.velocity.y; rb2d.velocity = new Vector2(Input.GetAxis("Horizontal"), yVel);

The problem is, it is getting the velocity (for me Y) and setting it, every frame, however the script is getting the velocity (for me y so i’m going to be saying it’s y) let’s say 1, so it sets it to 1, great right? wrong, gravity is constant, however the object is going from static to moving, so gravity accelerates the object, however the code rigidbody.velocity = new Vector2 (10f, rigidbody.velocity.y); will keep the y velocity constant, not allowing for the previously mentioned acceleration. to fix this, I made a variable, specifically for the Y velocity, but it gets set before the velocity does (it’s in the Update method), so the acceleration can happen.

I had a major problem with this and it was a Eureka moment xD