How can i do to pickup and drop an object with the same key?

How can i do to pickup and drop an object with the same key?

I tried everything I saw online, but nothing works, it never drops the object, even with a different key, the only way i found to drop the object is to do “if G is pressed, pickup and else if G is pressed drop” so it drops as soon as the object is picked up and I can’t do better.
I hope someone has a solution for me

Here’s my code:

if(grabCheck.collider != null && grabCheck.collider.tag == "objets")
{
    if(Input.GetKey("g"))
    {
        if(!isGrabbing)
        {
            grabCheck.collider.gameObject.transform.parent= Holder;
            grabCheck.collider.gameObject.transform.position= Holder.position;
            grabCheck.collider.gameObject.GetComponent<Rigidbody2D>().isKinematic = true;
            isGrabbing = true;
            if(isGrabbing == true)
            {
                Debug.Log("isGrabbing");
            }
        }
        else
        {
            grabCheck.collider.gameObject.transform.parent = null;
            grabCheck.collider.gameObject.GetComponent<Rigidbody2D>().MovePosition(grabDetect.position);
            grabCheck.collider.gameObject.GetComponent<Rigidbody2D>().isKinematic = false;
            isGrabbing = false;
            if(isGrabbing == false)
            {
                Debug.Log("isn't grabbing");
            }
        }
    }
    
}

1 Answer

1

Your strategy of using isGrabbing to determine what to do in response to the key being pressed sounds correct to me. I’m not sure about your grabCheck collider check since I don’t know how your scene is set up.

However, you may want to use Input.GetKeyDown instead of Input.GetKey. GetKey will return true on every frame that the key is in the down position, so you are likely toggling between holding and dropping every frame. GetKeyDown is only true for a single frame when the key is pressed. It won’t trigger again until you release and press the button again.

Please note that GetKeyDown only works at Update time. You shouldn’t try to use this in an OnCollisionEnter function or anything like that.

I tried Input.GetKeyDown but nothing changed, I tried to do "if(isGrabbing)[...] if(!isGrabbing)[...] instead of a if else condition and i think that it comes from the condition (if else/else if) bc he just grabs the object and drops it right after, I thought of using a while loop but it would be complicated as I'm new in c# and unity, in javascript or python i could do it but in c# I don't think so

When is the code in the original post run? Is it in Update or some other location? It may help to add more Debug.Log statements to determine if this is detecting more key events than you expect.

the code is in a function that i called grab() that i call in Update, i will try to add more Debug.Log statements but algorithmically i don't see anything wrong in my code