- Home /
Prevent picking up multiple items at same time
So I have completely functional scripts for picking weapons up and equipping them and such, but I have one problem. If the player is within range to pick up multiple items, all of the items will attempt to be picked up at the same time. How do I prevent this from happening and just pick up one item at a time?
You need to post up your code so we can analyze how your original script is working, so we can tell you how to prevent it.
First of all, it is important how you implement it. Do you have a crosshair and use Raycasting or how is the collecting process going on?
I only have two weapon slots. When the player is within a certain distance and the player presses "Q", the weapon is added to the empty weapon slot and set as the currently equipped weapon. If there was already a weapon equipped, that weapon is set as the secondary. If there were no empty slots when the player attempts to pick up the weapon, the current weapon is dropped and the weapon you picked up is set as the current weapon. I'm not going to post all of the code, there's quite a bit of it. Alternatively, having the weapon drops not be able to drop next to each other would probably work too.
It would behoove you to post the snippet of code that pertains to the pickup and assign portion of your script. I promise you, nobody here is going to s$$anonymous$$l your work, and even if they did, it's only a small part of it.
The answer depends on how you're implementing these mechanics, without the code, its hard to help you.
Not worried about code being stolen haha, I just wasn't sure what part of my code to post. Anywho's I figured it out and posted it as an answer to hopefully help someone who has the same problem in the future.
Answer by ToastandBananas · Jul 26, 2018 at 04:20 PM
Welp, figured it out. Basically it's this:
delay = 0.25f;
void OnTriggerStay2D(Collider2D collision)
{
if (collision.tag == "Player")
{
if (player.itemToPickup = null)
{
player.itemToPickup = gameObject;
}
player.timeSinceQPressed += Time.deltaTime;
if (player.timeSinceQPressed > delay)
{
if (Input.GetKeyDown(KeyCode.Q) && player.itemToPickup == gameObject)
{
// Run pick up and equip weapon code
player.timeSinceQPressed = 0;
player.itemToPickup = null;
}
}
}
}
I just made it so that the player can only pick up the assigned object and set a short delay until the player can pick up an item again (without the delay, multiple weapons were still trying to be picked up, sticky keyboard keys I think).
Your answer
Follow this Question
Related Questions
My Algorithm for checking whole tiles didint work 0 Answers
Side scroller spawns at different Y 1 Answer
how to stop player from automatically jumping on a moving platform 0 Answers
Unity - halo doesn't work all the time 0 Answers
Is it correct to animate the player spritesheet and external gameobjects in the same animation? 0 Answers