Jan Turoň
Jan Turoň

Reputation: 32922

Vector3.Set and Rigidbody2D.velocity.Set and function not working properly

In a simple movement script where body is gameObject.GetComponent<Rigidbody2D> (), movement is applied by this code

body.velocity = new Vector2 (10 * dir, body.velocity.y);

However in this one no movement (nor error) appears

body.velocity.Set (10 * dir, body.velocity.y);

I see no explanation in Unity documentation. Can you explain why body.velocity.x remains zero in the second case?

Upvotes: 3

Views: 1924

Answers (1)

Programmer
Programmer

Reputation: 125455

This is one of the mistakes people make while using Unity. You have to understand C# well to know what's really happening and why.

Here is why:

1.Rigidbody.velocity and Rigidbody2D.velocity are both types of Vector3 and Vector2.

2.Vector3 and Vector2 are both structs not class.

See struct vs class here for more info.

3.Rigidbody.velocity and Rigidbody2D.velocity are properties and uses a getter. This is means that it returns a copy of Rigidbody2D.velocity not the original variable or a reference of it because they are both structs as mentioned above.

See reference type and value type for more info on this.

4.When you call the Vector3.Set and Vector2.Set functions, you are calling that on a copy of a Vector3 and Vector2 not the actual or original Vector and this is due to #3.

If you really want to use the Set function on a Rigidbody create a different Vector variable you will be using to call that Set function on then assign the value to your Rigidbody.velocity.

For example,

Rigidbody2D body = null;
float dir = 4f;

Vector2 pos = Vector2.zero;

void YourFunction()
{
    pos.Set(10 * dir, body.velocity.y);
    body.velocity = pos;
}

Upvotes: 5

Related Questions