#Cant drop my key

1 messages · Page 1 of 1 (latest)

glass pagoda
#

I am trying to make a hold object function to my game, i can pick up a single item (objective) but then i cant drop it

⁨```cs
void HoldObject()
{
// is on raycast, E was pressed, isnt holding
if (CanInteract() && interactAction.WasPressedThisFrame() && !isHolding)
{
if (itemToHold == null) return;

        isHolding = true;
        Debug.Log("Grab: " + itemToHold);

        itemToHold.GetComponent<Rigidbody>().useGravity = false;
        itemToHold.transform.SetParent(objectHandle.transform);
        itemToHold.transform.position = objectHandle.transform.position;

    } // E was pressed, is holding something
    if (interactAction.WasPressedThisFrame() && isHolding)
    {
        if (itemToHold == null) return;

        isHolding = false;
        Debug.Log("Drop: " + itemToHold);

        itemToHold.GetComponent<Rigidbody>().useGravity = true;
        itemToHold.transform.SetParent(originalParent.transform);
    }
}

public bool CanInteract()
{
    RaycastHit hit;
    if (Physics.SphereCast(transform.position,
                         sphereRadius,
                         transform.forward,
                         out hit,
                         interactDistance,
                         interactable))
    {
        itemToHold = hit.collider.gameObject;
        return true;
    }
    else
    {
        return false;
    }
}
half flame
#

becasue you're doing:

        if (CanInteract() && interactAction.WasPressedThisFrame() && !isHolding) {
             ...
             isHolding = true;
             ...
        }
        // AND then you're immediately doing this:
        if (interactAction.WasPressedThisFrame() && isHolding) {
           // and here you drop the object
#

you also have a problem in that you are assigning your itemToHold variable in your function that is really just supposed to be raycasting

#

because that means while you are holding an object, you will potentially get a different object in that variable

#

and then when you drop you will try to drop that totally different object, instead of the one you're holding

#

I highly recommend making two separate variables:
raycastHitObject For the object your raycast hit this frame
holdingObject for the object you are currently holding, if any.

#

you can also then get rid of the isHolding variable because you can just say if (holdingObject != null) or if (holdingObject == null)

glass pagoda
glass pagoda
#

but im doing this here, is it wrong?

    itemToHold = hit.collider.gameObject;

or do i just change this "itemToHold" to raycastHitObject and use holdingObject as two separates variables as you said

#

ooh i think i get it

half flame
#

you are trying to use the same variable right now for two different purposes

glass pagoda
#

got it

glass pagoda
half flame
#

so they don't happen on the same frame

glass pagoda
#

ooohhh that makes very much sense lol