Error CS1612, CS1612, CS1612

Hi, can you help me please?
I have this errors:

Assets/Controller.cs(16,17): error CS1612: Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity'. Consider storing the value in a temporary variable
Assets/Controller.cs(18,17): error CS1612: Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity'. Consider storing the value in a temporary variable
Assets/Controller.cs(20,17): error CS1612: Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity'. Consider storing the value in a temporary variable

in this script:

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour
{
 

    void Update()
    {
        // Get the rigidbody component
        var r2d = GetComponent<Rigidbody2D>();

        // Move the spaceship when an arrow key is pressed
        if (Input.GetKey("right"))
            r2d.velocity.x = 10;
        else if (Input.GetKey("left"))
            r2d.velocity.x = -10;
        else
            r2d.velocity.x = 0;
    }
}

Thank you.

you cannot modify the individual components of velocity of the rigidbody so you need to create a new Vector3 from the current value, then modify the x component and store the velocity Vector3 back.

something like:

var newVelocity = new Vector3(r2d.velocity.x, r2d.velocity.y, r2d.velocity.z);
newVelocity.x = 10;
r2d.velocity = newVelocity;

do the firtst and last parts either side of your if statements

also, get the Component in Awake() or Start() instead of Update() - it’s way too slow to do every frame.

Thank you ! :slight_smile:
I took your advice.

Code is looks like there:
`

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour
{
r2d.velocity = newVelocity;

void Update()
{
    // Get the rigidbody component
   
    var newVelocity = new Vector3(r2d.velocity.x);
    

    if (Input.GetKey("right"))
        newVelocity.x = 10;
    else if (Input.GetKey("left"))
        newVelocity.x = -10;
    else
        newVelocity.x = 0;
 
   


}

}
`

Bud now, i have 2 errors:
Assets/Controller.cs(6,18): error CS1519: Unexpected symbol =' in class, struct, or interface member declaration Assets/Controller.cs(6,31): error CS1519: Unexpected symbol ;’ in class, struct, or interface member declaration

Thank you