So I was trying to follow some code I saw for a top down 2d character movement and wrote this:
rigidbody2D.velocity = new Vector2(
Mathf.Lerp(0, Input.GetAxisRaw("Horizontal") * speedModifier, 1f),
Mathf.Lerp(0, Input.GetAxisRaw("Vertical") * speedModifier, 1f)
);
However when I do that I get the error of:
Type UnityEngine.Component does not
contain a definition for velocity
and no extension method velocity of
type UnityEngine.Component could be
found. Are you missing an assembly
reference?
So I figured it was just a version change so I did the same thing I did for getting the Animator and added private Rigidbody2D rigidbody2D; and rigidbody2D = GetComponent<Rigidbody2D>(); to the Start() method and while that makes the code work, I get this waring:
PlayerController.rigidbody2D hides
inherited member
UnityEngine.Component.rigidbody2D.
Use the new keyword if hiding was
intended
What am I doing wrong? What is the correct way to access the Rigidbody2D Component without getting a warning / error and have the code work?
ryanzec
3
From what I have gathered, it seems like rigidbody2D is an automatically created property in the script however it is not preferred to use GetComponent but the old property is still there so tried to override it causes the warning. To get rid of the warning and use the GetComponent way of getting the rigidbody2D I just needed to add new to the property definition like new private Rigidbody2D rigidbody2D;.
All your code seems correct. can u send the entire script
I used GetComponent<Rigidbody2D>() and that worked for me but I don’t know if that would work for you too. I’m just a beginner.