So I have been following a tutorial about 2d movement in Unity and the video run the code successfully. However, when I run the code, Unity said: line
public Vector2 Velocity => rigidBody2D.velocity;
is error and it force me to use GetComponent instead. So I follow the it and change the code to:
public Vector2 Velocity
{
get => GetComponent<Rigidbody2D>().velocity;
set => GetComponent<Rigidbody2D>().velocity = value;
}
Am I doing it correctly?
CodePudding user response:
Yes your variant is legitimate way to go about it, tho it is much more common to see the following:
private Rigidbody2D rb2d;
public Vector2 Velocity;
void Start(){
rb2d = GetComponent<Rigidbody2D>();
}
void Update(){
rb2d.velocity = Velocity;
}
My only recommendation to you would be to get the reference in Start as well, since using GetComponent all the time is a bit wasteful performance vise.
CodePudding user response:
Using GetComponent<Rigidbody2D>()
instead of the obsolete Component.rigidbody2D
is good.
However storing the object returned instead of looking it up each time when you need to refer to it including during the call to your Velocity
property is better. This will lead to better performance.
Change:
public Vector2 Velocity
{
get => GetComponent<Rigidbody2D>().velocity;
set => GetComponent<Rigidbody2D>().velocity = value;
}
...to:
public Vector2 Velocity
{
get => GetComponent<Rigidbody2D>().velocity;
set => GetComponent<Rigidbody2D>().velocity = value;
}
private Rigidbody2D _rigidBody;
private Start()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
public Vector2 Velocity
{
get => _rigidBody.velocity;
set => _rigidBody.velocity = value;
}