Simple rigidbody movement problem

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

public class PlayerMovement : MonoBehaviour {
   
    private Rigidbody rb;

    public Transform playerCamera;

    public float speed;
    public float jumpForce;

    private bool grounded = false;

    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    void Update() {
        float x = Input.GetAxisRaw("Horizontal");
        float z = Input.GetAxisRaw("Vertical");

        rb.velocity = new Vector3 (x, rb.velocity.y, z) * speed;

        if (Input.GetKeyDown("space")) {
            rb.AddForce(Vector3.up * jumpForce);
        }
    }

    void OnCollisionStay () {
        grounded = true;
    }
}

It says that the field grounded is assigned but its value is never used, why?

Because … it’s never used? Show me above where you think you are using the value. I only see you assigning to it, never reading from it. That’s what “using” means in this context.

So how am I supposed to use grounded to detect when I’m on the ground?

Whereever you wanna check if your player is on the ground you have to check it

if (grounded)
{
    // do something...
}

In your case the check should be done, before you jump, so on line 27 i guess.

1 Like

There are many steps to ground checking, and they are already well understood.

You need a variable - check, you got that

You need to set it when on the ground -check, you got that

You need to clear it (set it to false) when you’re NOT on the ground - missing as far as I can tell

You need to use that variable for whatever you want - missing as far as I can tell.

Since this looks like just a bog-standard basic movement controller, why not start with one of the already-complete ones out there and learn from it first?

Once it’s working, then you can go roll your own and have all the benefit of standing on the shoulders of people who solved this ultra-simple ultra-common problem already.

Here’s a vast repository of random character controllers of various kinds:

https://wiki.unity3d.com/index.php/Scripts/Controllers

1 Like

Ohhh you’re right, I’m so dumb for not seeing this, no wonder when I collide nothing happens.
Thanks for giving an example for dummies.