- Home /
IF statement ignoring condition
So ive been working on a game where the player can shift its shape when press J, K, or L key. The problem is I want to restrict the player from pressing the same key twice so i code some if statement as below:-
public GameObject sphere;
public GameObject cube;
//public GameObject pyramid;
bool keypressJ = false;
bool keypressK = true;
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.J) && keypressJ == false)
{
sphere.transform.position = cube.transform.position;
sphere.SetActive(true);
cube.SetActive(false);
//pyramid.SetActive(false);
keypressJ = true;
keypressK = false;
Debug.Log("keypress J = " + keypressJ);
}
if (Input.GetKeyDown(KeyCode.K) && keypressK == false)
{
cube.transform.position = sphere.transform.position;
cube.SetActive(true);
sphere.SetActive(false);
//pyramid.SetActive(false);
keypressJ = false;
keypressK = true;
Debug.Log("keypress J = " + keypressJ);
}
when i run the game it run perfectly on the first shift. but after it returns to cube shape, i cant shift it back to sphere. i have look around for answer but still couldnt find any. this is my first time posting on the community so i hope my question is clear enough. any help is very much appreciated.
@Arashio I ran the script myself, and I get no errors. Is this script attached to one of the objects, or is it a separate object? If it's attached to one of the objects, what happens is that when you disable the object, all components stop as well, thus the script never runs again
Answer by hexagonius · Oct 10, 2018 at 08:53 PM
what about this solution: save the keycode pressed if valid and do the transformation. always check and who's the current saved keycode. that should already do it.
note: if you already have something that can be used for if checking, don't so additional bools you need to handle.
I ran the script myself and I got no errors; perhaps it isn't an actual scripting error.
Answer by Bunny83 · Oct 10, 2018 at 09:16 PM
Do never check down or up events (or generally anything that is only true for one frame) inside FixedUpdate. Those things can only be done in Update. FixedUpdate does not necessarily run every frame and can miss such events.
Your answer
Follow this Question
Related Questions
How come my camera does not follow my script? 1 Answer
Why simple letter evaluataion returns true no matter witch letter 1 Answer
Coroutine freezes editor but only sometimes. Why ? Why is it happening randomly ? 3 Answers
Unity freezes after running this basic code. 2 Answers
How to call unity event once every time my object reach destination in Update()? 1 Answer