Missing Component: Rigidbody. When there is a rigidbody component attached.

Hi,

I’m currently trying to complete the survival shooter unity tutorial.

I’ve hit a strange wall, my code is exactly as the complete code is shown:

using UnityEngine;


public class PlayerMovement : MonoBehaviour
{
    public float speed = 6f;

    Vector3 movement;
    Animator anim;
    Rigidbody playerRigidbody;
    int floorMask;
    float camRayLength = 100f;

    void Awake () {

        floorMask = LayerMask.GetMask ("Floor");
        anim = GetComponent<Animator> ();
        playerRigidbody = GetComponent <Rigidbody> ();
        Debug.Log ("awake");

    }

    void Start () {

    }

    void FixedUpdate () {

        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Debug.Log (h);
        Debug.Log (v);
        Debug.Log ("update");
        Move (h, v);
        Turning ();
        Animating (h, v);

    }

    void Move (float h, float v) {
   
        movement.Set (h, 0f, v);

        movement = movement.normalized * speed * Time.deltaTime;

        playerRigidbody.MovePosition (transform.position + movement);


    }

    void Turning () {

        Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit floorHit;

        if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) {
            Vector3 playerToMouse = floorHit.point - transform.position;
            playerToMouse.y = 0f;

            Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
            playerRigidbody.MoveRotation (newRotation);
        }

    }

    void Animating (float h, float v) {
        bool walking = h != 0f || v != 0f;
        anim.SetBool ("IsWalking", walking);
    }

}

However when it runs I get this error:

Even though as you can see there is in fact a rigidbody component on the GameObject the script is attached to.

Any ideas what could be causing this?

Try this.gameObject.GetComponent() - similar stuff was happening to me as well until I’ve started to write this like that.

Didn’t change anything sadly, same error message. It appears adamant that there is no rigid body attached to the object. Could there be something wrong with the rigidbody component?

I don’t know why but I had to delete the player gameobject and just re-create it. It really didn’t like it for some reason, all seems fixed now.

I think i know what you did as i just did the same thing, you probably added the PlayerMovement script to the player 3d model child object whereas it needs to be attached to the parent object, where the rigid body is stored.

2 Likes

I had the same problem with my asteroids. The model “prop_asteroid_01” also had “Mover” script as a component, but since my rigidbody component was on the parent “Asteroid” (which also had the script “Mover”), I only had to delete the script from the child and it didn’t give me the error anymore.