- Home /
Trying to Swap 2 Weapons
Hello,
I am relatively new to Unity and am currently going crazy because of a problem.
in a 2D topdown game I try to swap my current weapon with the weapon lying on the ground. Both have the "WeaponSystem" script with the following code for pickup/drop:
private void Update()
{
MyInput();
}
private void MyInput()
{
if(Input.GetKeyDown(KeyCode.E) && findPlayerInRadius.inRange && !isActive)
{
GameObject activeWeapon = pivotpoint.transform.GetChild(0).gameObject;
activeWeapon.GetComponent<GunSystem>().Drop();
PickUp();
}
}
private void PickUp()
{
isActive = true;
//Attach Weapon to Player
transform.parent = pivotpoint.transform;
transform.localPosition = pos;
transform.localRotation = Quaternion.identity;
transform.localScale = new Vector3(1, 1, 1);
}
private void Drop()
{
isActive = false;
//Unattach Weapon to Player
transform.parent = null;
transform.localRotation = Quaternion.identity;
transform.localScale = new Vector3(1, 1, 1);
}
According to the Visual Studio Debugger, the process now looks as follows: The MyInput() method is called for my object lying on the ground which has the effect that the active weapon is dropped and is therefore no longer "active". The weapon lying on the ground is then picked up and set "Active".
So far so good.
But then the problem occurs: the MyInput method is called again for the originally active weapon which is now lying on the ground. This has the effect of picking up the weapon and dropping the other one. In the game it looks like I don't pick up the other weapon at all, because it is dropped again immediately.
Unfortunately, I don't know how to get ahead at this point.
I hope you can help me^^
Answer by revolute · Aug 21, 2020 at 10:21 AM
The problem here is that you are taking input per object. On a single frame, if the item lying on the ground gets updated first and then the weapon you are holding gets updated next, then it will simply pick up the ground weapon first then immediately swap for the gun you just dropped. If you're going down this road, put a delay in picking up weapons.
ok i will try that. do you have any tips how i can do this? the first thing i see is the invoke method
Using an IEnumerator will allow you to delay a set of instructions by a specified amount of time. For example:
IEnumerator SwitchWeapons()
{
yield return new WaitForSeconds(0.5f); //Delays for 0.5 seconds
PickUpWeapon();
}
void PickUpWeapon()
{
//...
}
$$anonymous$$ake sure that you have the using System
tag at the top to get the IEnumerator class.
Your answer
![](https://koobas.hobune.stream/wayback/20220613010059im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D top-down multiple sprite rotation 1 Answer
Touch Buttons 0 Answers
Lines are disappearing and merging as I zoom out 2 Answers
2D Top Down Shooter Shooting Problems 1 Answer
8-directional orientation, top down 2D, seperate from movement 0 Answers