How to use GetComponent<Rigidbody2D>()

I’ve been trying my best to google but I honestly am still confused.

Trying to look up tutorials and get myself acquainted. First problem was trying to convert

rigidbody2D.velocity = new Vector2( 0, jumpHeight);

to

GetComponent()

I made rigidbody2D = GetComponent(), but then I get

UnityEngine.Component does not contain abstract definition for velocity and no extension method etc…

I just wanna make my character be able to jump up, any help is appreciated!

Try to cast the GetComponent() with an “as RigidBody2D” like that:
var rigidBody = GetComponent() as RigidBody2D;

It should work without the cast tho.

Could you send your code please?

Forgive me if this is wrong, shouldn’t you type cast your variable?

//<type>
RigidBody2D rigidbody2D = this.gameObject.GetComponent<Rigidbody2D>();

I read Unity - Scripting API: Rigidbody2D.velocity
It says velocity returns an x and y vector…
so

rigidbody2D.velocity = new Vector2( 0, jumpHeight);

should work. I’ll test this.

Don’t name your variable rigidbody2D. This is the same name as an existing deprecated property on MonoBehaviour. Call it anything else and the script will work.

3 Likes

Basically anything you get out of GameObject.GetComponent<>() needs to have it’s type casted.

1 Like

That is absolutely incorrect.

2 Likes

Assuming you do have a RigidyBody2D component on your object (I myself tend to miss this part quite often :smile: )
You may give it a force with a vector showing up using the AddForce function.

Stop mucking the thread up with wrong answers folks. @Kiwasi was correct

:slight_smile:

2 Likes

The generic version will always return the type passed in. That’s the whole point of the generic function and angle brackets. Casting is a total waste of time and performance.

The non generic version does return a component, and needs to be casted. But using the non generic version is limited to some special use cases. These are way beyond the OP at present.

Missing a RigidBody would throw a null reference error. Different problem.