How can I restrict player movement to the edges of the plane so that they don't fall off the platform?

Right now I have a basic cube and a plane; the cube is the player and the plane is the platform. I’ve managed to create player movement on the plane, but I’m not sure how to restrict the cube to the plane so that the player doesn’t fall off. I’ve seen examples where people have used “if (transform.x.position> a number value)…”, but is there a way to restrict it to my plane specifically?

The only script I have is for the cube at the moment and my screen looks like this:

Here is my script for the cube so far:

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

public class cubeControls : MonoBehaviour
    public float moveSpeed = 0.5F;
    public Rigidbody player;

    // Start is called before the first frame update
    void Start()
        // Setting the cube (player) color to red
        Renderer rend = GetComponent<Renderer>();

        // Needed to use rigid body methods
        player = GetComponent<Rigidbody>();

    // Update is called once per frame
    void Update()
        // Moving the object right
        if (Input.GetKey(KeyCode.RightArrow))
            player.MovePosition(transform.position + transform.right * Time.deltaTime);

        // Moving the object left
        if (Input.GetKey(KeyCode.LeftArrow))
            player.MovePosition(transform.position + transform.right * -Time.deltaTime);

        // Moving the object forwards
        if (Input.GetKey(KeyCode.DownArrow))
            player.MovePosition(transform.position + transform.forward * -Time.deltaTime);

        // Moving the object backwards
        if (Input.GetKey(KeyCode.UpArrow))
            player.MovePosition(transform.position + transform.forward * Time.deltaTime);


There are a lot of ways of doing it, using the unity physics system and just put colliders at the edge, you can use raycast from the edges of the players to Vector3.down and if they stop detecting the square just dont let the player move in that direction, or compare the player position and make sure its not passing the object size thats just up to you and probably there are other ways of doing this.

You could use Clamp() if you want to avoid using physics. I’d recommend instead of applying the movement immediately after input that you collect it all and then apply the movement in one line of code. Another option is to check the player’s position in your if statement.