- Home /
How do you use the same key for two different conditions.
Sorry if this seems like a dumb question to ask. I am fairly new to unity.
Anyways, I would like my player to pick up an object. I would like to use the same key (E) to pick the object up and also place it down if the player is holding it. I haven't really been able to get it to work.
Code:
Answer by sacredgeometry · Dec 28, 2020 at 08:38 PM
Something like?
var canHold = item.tag == "Grabable";
if((canHold || isHolding) && Input.GetKeyDown(KeyCode.E))
{
if(isHolding)
{
PutdownItem();
}
else
{
PickupItem();
}
}
I didn't think about that! It would also make the code cleaner.
I have updated it with the case for is holding because I don't know how item is populated and if its transient or not.
Answer by AmateurPrograming · Dec 28, 2020 at 09:13 PM
It kind of works, yet the thing I am trying to pick up freaks out for some reason. Sometimes if I press E it doesn't pick up or put down fully. It will just appear to be placed or picked up for a split second then go back to its normal position.
I wasn't having an issue like this when I used separate keys to pick up and place the object.
I also changed a bit of your code to fit mine.
New Code (Including some more):
Use Input.GetKeyDown not Input.GetKey.
One repeats for as long as you have it held down the other just does it once.
I changed "GetKey" to "GetKeyDown". It takes more keypresses to drop the object.
It sounds like you have a bunch of bools and are trying to juggle state between them needlessly and various combinations of that state are resulting in working and others arent.
I would try to simplify it or failing that make sure you are managing the state properly.
Its hard to tell without seeing all of the relevant code
Fixed it, I changed FixedUpdate to Update.
Never$$anonymous$$d, it still can take multiple keypresses until you pick up or drop the object.