- Home /
Pick up script goes straight to drop action
I have this script to pick up and hold items but when I try to pick up an item it goes straight to the drop action.
using UnityEngine;
using System.Collections;
#pragma warning disable 0414
namespace CarryingItems {
public class PickUp : MonoBehaviour {
// publics
public bool NearObject;
// Where to place the item.
private GameObject Hand;
// The object I'm carrying.
public static GameObject CarriedObject;
public LayerMask RayMask;
// privates
// The parent.
private GameObject UtilityProps;
private Rigidbody CORB;
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 (CarriedObject != null) {
ItemDrop();
}
else if(CarriedObject == null) {
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;
CORB = CarriedObject.GetComponent<Rigidbody>();
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.
Comment
Your answer
Follow this Question
Related Questions
Item pickup and drop function 2 Answers
Multiple Cars not working 1 Answer
Unity/Mono Develop Bug 1 Answer
Distribute terrain in zones 3 Answers
Bugs in a pick up items script. 2 Answers