Simple transform position through velocity from JavaScript to C#

The code is javascript but I want to translate it too C# because I want to be able to refrence a different C# script. Thanks so much for the help.

GetComponent.().velocity.x = speed;

To get a component in unity, you need to do GetComponent<ComponentType>(). For example, GetComponent<Rigidbody2D>() will give you the Rigidbody2D component of your GameObject, if it’s attached.

This is because, contrary to Javascript, C# is a strongly typed language and GetComponent() is a generic method. This means you can do

Rigidbody2D rb = GetComponent<Rigidbody2D>();

and not have to worry about runtime exceptions, which is a strong feature of object oriented languages.

Also, you can’t generally directly assign the x, y or z values of the Unity Engine’s components vectors in C# because they are implemented as properties instead of variables (which are getters and setters that you can call like variables), so you have to assign the whole vector to it. Here is what you could do:

Rigidbody2D rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed, rb.velocity.y);

That way, you change the x component of the velocity, and set the y component exactly as it was before. If you are working in 3D instead, you only need to use a Rigidbody instead of a Rigidbody2D component:

Rigidbody rb = GetComponent<Rigidbody>();
rb.velocity = new Vector3(speed, rb.velocity.y, rb.velocity.z);

If you are new to C# or object oriented languages in general, it might seem like a lot of new stuff, but it’s worth it since those languages are so widely used. Here are a few links if you want to learn more: