简体   繁体   中英

How to fix "rigidbody2D is obsolete" error

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM