Thursday, November 6, 2014

Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity'. Consider storing the value in a temporary variable



Unity Sample Code :

rigidbody2D.velocity.y = speed;

The above C# code won't show any syntax error. But unity 4 and above will throw runtime error saying

"Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity'. Consider storing the value in a temporary variable"



Since we are trying to modify the velocity of the object without assign the object into a variable.

The below code will run as expected.

Vector2 vel = rigidbody2D.velocity;
vel.y = speed;
rigidbody2D.velocity = vel;

Similiar coding style when writing coding in javascript on Unity 4.


    Choose :
  • OR
  • To comment