- Home /
 
rigidbody.velocity problem
Hey I was wondering why this line of coding is not working. I am getting the following error: "Cannot modify a value type return value of `UnityEngine.Rigidbody.velocity'. Consider storing the value in a temporary variable". Anybody know what I can do?
Update: When the rigidbody.velocity line variable is above the horizontalMovement, than I get very jerky results but the stopping works. If I do it vice versa, movement works fine but stopping doesn't.
 //Checks how fast player is moving
     horizontalMovement = new Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
     rigidbody.velocity = new Vector3(horizontalMovement.x, rigidbody.velocity.y, horizontalMovement.y);
         
     //If movement exceeds Max Walk Speed
     if(horizontalMovement.magnitude > maxWalkSpeed)
         {
         //Normalize it
         horizontalMovement = horizontalMovement.normalized;
         //Reset it to Max Walk Speed
         horizontalMovement *= maxWalkSpeed;
         }
     
     if(Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0 && grounded == true)
         {
             Vector3 velocity = rigidbody.velocity;
             velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, ref walkDeaccelerationVolx, walkDeacceleration);
             velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, ref walkDeaccelerationVolz, walkDeacceleration);
             rigidbody.velocity = velocity;
         }
         
 
              Answer by robertbu · Sep 27, 2013 at 06:15 PM
In C# you have to do:
 Vector3 velocity = rigidbody.velocity;
 velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, ref walkDeaccelerationVolx, walkDeacceleration);
 velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, ref walkDeaccelerationVolz, walkDeacceleration);
 rigidbody.velocity = velocity;
 
               Note typing the error message along the word "Unity3d" into Google will get you lots of hits/solutions for most Unity errors.
I googled it but didn't get any useful results, hence I had to ask here. Thanks for your reply. I updated the script but when the player doesn't press the buttons he doesn't slow down. Any idea why? I think this is how you meant it to be used, right?
 if(Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0 && grounded == true)
         {
             Vector3 velocity = rigidbody.velocity;
             velocity.x = $$anonymous$$athf.SmoothDamp(rigidbody.velocity.x, 0, ref walkDeaccelerationVolx, walkDeacceleration);
             velocity.z = $$anonymous$$athf.SmoothDamp(rigidbody.velocity.z, 0, ref walkDeaccelerationVolz, walkDeacceleration);
             rigidbody.velocity = velocity;
         }
 
                 I don't see anything in this code that would account for what you describe. Is there any other code that accesses the keys?
Your answer