I have this script to pick up and hold items and it works fine but I have to press E three times to drop an object. I have tried to use debug.logs and it showed me that everything else is working (the hierarcy, colliders, etc.) except for the positioning.
This is my script:
using UnityEngine;
using System.Collections;
#pragma warning disable 0414
namespace CarryingItems {
public class PickUp : MonoBehaviour {
// publics
// The parent.
private GameObject UtilityProps;
// Where to place the item.
private GameObject Hand;
// The object I'm carrying.
public static GameObject CarriedObject;
public LayerMask RayMask;
// privates
public bool NearObject;
private bool ItemPickedUp;
private float OffsetDropPosition = 2;
private RaycastHit FilterHit;
void Awake() {
UtilityProps = GameObject.Find("UtilityProps");
Hand = GameObject.Find("ItemHand");
}
void Update() {
NearObject = PickUpSphereCasts.NearObject;
if (Input.GetKeyDown(KeyCode.E)){
if (ItemPickedUp == true) {
ItemDrop();
}
else if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out FilterHit, RayMask.value)){
ItemPickUp(FilterHit.collider.gameObject);
}
}
}
void ItemPickUp(GameObject objectToPickup) {
// unless you've set your LayerMask to only hit the objects that can be picked up (you should do this as well, for optimization purposes), you must check if you can pick up this object
if (objectToPickup.layer != 8) { // if you can't pick it up, do nothing then leave this function
return;
}
if(NearObject == true){
// from now on we know we are holding an item
ItemPickedUp = true;
// make the scene modifications
CarriedObject = objectToPickup;
CarriedObject.transform.SetParent(Hand.transform, false);
CarriedObject.GetComponent<Rigidbody>().useGravity = false;
CarriedObject.GetComponent<Rigidbody>().isKinematic = true;
CarriedObject.transform.position = Hand.transform.position;
CarriedObject.transform.rotation = Hand.transform.rotation;
CarriedObject.gameObject.GetComponent<Collider>().enabled = false;
}
}
void ItemDrop() {
// from now on, we do not have an object picked up
ItemPickedUp = false;
// make the scene modifications
CarriedObject.transform.SetParent(UtilityProps.transform, false);
CarriedObject.transform.position = Camera.main.transform.position + Camera.main.transform.forward * OffsetDropPosition;
CarriedObject.transform.rotation = Hand.transform.rotation;
CarriedObject.GetComponent<Rigidbody>().useGravity = true;
CarriedObject.GetComponent<Rigidbody>().isKinematic = false;
CarriedObject.gameObject.GetComponent<Collider>().enabled = true;
// clear the reference
CarriedObject = null;
}
}
}
Any help is appreciated.
EDIT: I tried @UnityCoach’s idea but the script went straight to the drop action.