Picked up items being added multiple times on the inventory list.
Hello everyone. I'm having some trouble trying to code a "pick up a weapon" script and a "switch weapon" script.
In my game, the player have 3 weapons available, but he must pick it up first in order to use it.
I have the weapons attached to the player and other models on the floor. When the user pick up a weapon, the one that is onde the floor is destroyed and the other (attached to the player) is rendered. The problem that I have is that the code is being executed three times (thus adding multiple times the same weapon) but I can't get this while debugging (it works fine the debug mode). This is the code to the method and I'm calling it when the player presses the "F" key on update.
private void PickUpWeapon()
{
if (mWeapons.Count <= 0)
{
GameObject.Find(mColliderName + " On Player").GetComponent<MeshRenderer>().enabled = true;
Destroy(GameObject.Find(mColliderName));
mWeapons.Add(GameObject.Find(mColliderName + " On Player"));
mWeaponActive = mColliderName;
Debug.Log("Count: " + mWeapons.Count);
}
else
{
GameObject.Find(mWeaponActive + " On Player").GetComponent<MeshRenderer>().enabled = false;
GameObject.Find(mColliderName + " On Player").GetComponent<MeshRenderer>().enabled = true;
Destroy(GameObject.Find(mColliderName));
mWeapons.Add(GameObject.Find(mColliderName + " On Player"));
mWeaponActive = mColliderName;
Debug.Log("Count: " + mWeapons.Count);
}
}
The other problem is that I can't figure out how to switch between them. I've tried to use a list (mWeapons) and them get the index and switch it, but becaude this list has the weapons multiple times, it doesn't work properly. Can someone enlighten me how to fix this? Should I use the Fixed Update method? Thanks for the attention in advance.
Answer by mvpires · Mar 09, 2016 at 07:37 PM
I think I fixed the main problem.
This is the code where I call the PickUpWeapon method:
if(mInTrigger && Input.GetKey(KeyCode.F))
{
PickUpWeapon();
}
mInTrigger is a flag that I use to verify if the player is in the trigger zone to be able to pick up the weapon. Turns out I wasn't "turning it off" by setting it "false" and this probably made the code run multiple times. I fixed it by simply setting it false.
if(mInTrigger && Input.GetKey(KeyCode.F))
{
PickUpWeapon();
mInTrigger = false;
}
Now I need to figure it out how to properly switch weapons.
Your answer
Follow this Question
Related Questions
Missing ',' when there is no need? 0 Answers
How would i change my mouse cursor in between scenes 0 Answers
Start() and Update() execution issue 6 Answers
Vector3.Lerp in update, how stop? 1 Answer