Search code examples
unity-game-enginegame-physicsunityscriptrigid-bodies

What is the code to add physics to the rigidbody in unity 5.0.0p2?


The following code seems to be wrong in Unity 5.0.0p2:

rigidbody2D.velocity.x = Input.GetAxis("Horizontal") * 10;

So I tried the following code:

GetComponent<Rigidbody2D>().velocity.x = Input.GetAxis("Horizontal") * 10;

But still it is not working. Several error messages appear as follows.

  • BCE0043: Unexpected token: ).
  • BCE0044: expecting ), found '.'.
  • UCE0001: ';' expected. Insert a semicolon at the end.

What is wrong with my code?


Solution

  • Your first line will no longer work because rigidbody2D is no longer a property of a MonoBehaviour. This has been removed, so you will have to use a GetComponent<Rigidbody2D>() instead.

    That doesn't fully fix your problem however. You cannot update a velocity like you do, by only setting the x value. You will have to assign the full vector. So copy your current velocity to a Vector3 of its own, update x and replace the whole velocity vector.