grab and drop problem

i have a script that allows me to pick up and drop an object based on two buttons. one button allows me to drop the object, and the other button allows me to pick it up. my problem is that im getting confused on how to make it so that when i pick another object up, that the current object is being dropped. its a bit confusing so heres an example.

i grabbed object1 and now i want to be able to grab object2 but when i do grab object2, i want object1 to be dropped and so on. based on two buttons. one for drop, one for pickup. hopefully its understandable.

heres the current scrip im using. it allows me to grab one object only and to drop it, but i dont know how to make it a working cycle.

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using UnityEngine;

public class pickthrow : MonoBehaviour
{
    public Camera fpsCam;
    public float distance = 10f;

    public GameObject ButtonGrab;
    public GameObject ButtonDrop;
    public Transform equipPosition;

    void FixedUpdate()
    {
        RaycastHit hit;

        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, distance) && hit.transform.gameObject.tag == "CanGrab")
        {
            ButtonGrab.SetActive(true);
        }

        else
        {
            ButtonGrab.SetActive(false);
        }

    }

    public void Grab()
    {
        ButtonDrop.SetActive(true);
        this.gameObject.transform.position = equipPosition.position;
        this.gameObject.transform.parent = equipPosition;
        this.gameObject.transform.localEulerAngles = new Vector3(95f, 2f, 130f);
        this.gameObject.GetComponent<Rigidbody>().isKinematic = true;
    }

    public void Drop()
    {
        ButtonDrop.SetActive(false);
        this.gameObject.transform.parent = null;
        this.gameObject.GetComponent<Rigidbody>().isKinematic = false;
    }
}

Please don’t write lines of code like line 20 above. You really only hurt yourself.

Break it out into many separate lines of code, each doing (ideally) one step of the problem at a time, saving intermediate results to temporary variables so that you can output them with Debug.Log().

Here’s some general guidance:

http://plbm.com/?p=248

That way, you have a fighting chance to reason about what is happening one thing at a time, not just as one giant blob of crazy logic.

Also, always reach for liberal sprinkles of Debug.Log() all over the code to figure out what object is being handled, is the code even running, etc.

1 Like