I am working on a simple weapon pickup script and am having some trouble.
When i Press my E button to call for my Pickup() method, it also calls for my Drop() method.
I would like to use the same button to pickup and drop my weapons but I’m not sure how to fix this. I’ve tried using an IEnumerator to wait half a second then to make the isheld true but that didnt seem to work.
Please if anyone has any advice or suggestions that’ll be very helpful!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemPickup : MonoBehaviour
{
public bool PickupAllowed = false;
public float Pickupradius;
public Transform PickupSpot;
public LayerMask PlayerLayer;
public Transform NewPosition;
private bool IsHeld = false;
//private bool iscurrentlyholding = false;
public GameObject PlayerParent;
void Update()
{
//check if the items in range
PickupCircle();
//pickup the item
if (PickupAllowed == true)
{
if (Input.GetKeyDown(KeyCode.E) && IsHeld == false)
{
Pickup();
Debug.Log("Pickup is called");
}
if (Input.GetKeyUp(KeyCode.E))
{
IsHeld = true;
}
}
//drop the item
if (IsHeld == true)
{
if(Input.GetKeyDown(KeyCode.E))
{
Drop();
Debug.Log("Drop is called");
}
if (Input.GetKeyUp(KeyCode.E))
{
IsHeld = false;
Debug.Log(IsHeld);
}
}
}
private void PickupCircle()
{
if(Physics2D.OverlapCircle(PickupSpot.position, Pickupradius, PlayerLayer))
{
PickupAllowed = true;
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(PickupSpot.position, Pickupradius);
}
private void Pickup()
{
gameObject.transform.position = new Vector2(NewPosition.position.x, NewPosition.position.y);
gameObject.transform.parent = PlayerParent.transform;
}
public void Drop()
{
gameObject.transform.parent = null;
gameObject.transform.position = new Vector2(transform.position.x, transform.position.y);
}
}