You want the player to only drop the object when they let go of the button, right? In that case, I think this else clause is in the wrong place.
else
{
holding = false;
}
Right now it is the else clause for if(holding == false) but I assume you want it to be the else clause for if (Input.GetKeyDown(KeyCode.Mouse0))
Edit: Actually, I just looked at your code again, and it appears that there’s nothing from preventing the player from picking up more than one box. It looks like you are trying to limit the player to picking up one box by using the “holding” variable to determine if the player is already holding a box. This won’t work because each box has its own “holding” variable. If you set holding to true for one box, all of the other boxes will still have holding set to false.
thanks for the assistance I however found a different approach I’m now currently checking the bool and the transform of the object to make sure its grabbing the right one
public class Box : MonoBehaviour
{
public Transform hands;
public bool holding = false;
Rigidbody rb;
public Transform box;
Transform check;
void Start()
{
check = GetComponent<Transform>();
rb = GetComponent<Rigidbody>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if(holding == false)
{
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.tag == "box")
{
holding = true;
box = hit.transform;
Debug.Log(hit.collider.gameObject.name);
}
}
}
else
{
holding = false;
}
}
if(holding && check == box)
{
box.position = hands.position;
box.transform.rotation = hands.rotation;
this.rb.useGravity = false;
}
else
{
rb.useGravity = true;
}
}
}
All the boxes have code on them that says “if the player presses Mouse 0, and there’s a box in front of the player, pick me up”. Which causes all of them to be picked up if one of them is picked up.
Most of that code should be on a single object rather than all of the boxes.
The Second Set of Code I posted works just for anyone who has this problem in the future I made it so it checks if it hit the box and it checks which box it hit.
Here its shows where it defines the check and box in different places of my previous post NOTE: THIS. DOES. WORK.