Player can grab objects from any distance even when limited

So I created a mechanic where the player is able to control certain platforms while on them, but something goes wrong and Im able to grab the platforms from any distance. Heres the script ( this script its used in all the platforms/game objects that the player is allowed to control):

public class GrabItem : MonoBehaviour
{


    public GameObject character;
    public bool canGrab;
    private Rigidbody rb;
 

    void Start()
    {

        rb = GetComponent<Rigidbody>();

    }

    //Detects if the player collides with the special platforms

    void OnCollisionStay(Collision coll)
    {
        if (coll.gameObject.tag == "Player")
            canGrab = true;

    }
    void OnCollisionExit(Collision coll)
    {
        if (canGrab)
        {
            canGrab = false;

        }

    }

    //If the player dies the platform returns to his initial position, rotation and scale

    void FixedUpdate()
    {
   
     //The player is allowed to control a platform when he collides with it and its holding the O key
  
        if (canGrab = true & Input.GetKey(KeyCode.O))
        {

            this.transform.parent = GameObject.Find("character").transform;
            rb.constraints = ~RigidbodyConstraints.FreezePositionZ;
         
        }

        else
        {

            rb.constraints = RigidbodyConstraints.FreezeAll;
            this.transform.parent = null;
        
        }



    }




}

Removed some parts so its easier to understand

if (canGrab = true & Input.GetKey(KeyCode.O))

There are a few errors in this line. You’ll want == and && instead of the ones you have there.

1 Like

Works perfectly thank you so much, I though = and == was the same, Im gonna search up for the diferences (Im kinda new with C#)

= is an assignment, whereas == is a comparison.
Example:

//Here, I am declaring an integer and assigning it's value to 5.
int x = 5;

//Here, I am checking if the value of this integer is equal to 5.
if(x == 5) {
   //This block of code will execute if x equals 5.
}
else {
   //This block of code will execute if x does not equal 5.
}
1 Like