Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot implicitly convert type 'UnityEngine.Rigidbody2D' to 'UnityEngine.Rigidbody' error in Unity 2D core

I am new to Unity and I am following a tutorial, but when I write the code I get this error:

Cannot implicitly convert type ‘UnityEngine.Rigidbody2D’ to ‘UnityEngine.Rigidbody’

The code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCtrl : MonoBehaviour
{
    public float movSpeed;
    float speedX, speedY;
    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        speedX = Input.GetAxisRaw("Horizontal") * movSpeed;
        speedY = Input.GetAxisRaw("Vertical") * movSpeed;
        rb.velocity = new Vector2(speedX, speedY);
    }
}

How can I fix this?
I tried debugging and rewriting the code and the issue persists.

>Solution :

Your rb variable in the PlayerCtrl class has the type for a 3D rigidbody:

Rigidbody rb;

Change it to Rigidbody2D instead:

Rigidbody2D rb;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading