If statements contradicting themselves?
I have a detection script for interacting with things in my game, but I think the IF statements mess with each other. I have tried many things, like separating them into different methods, changing the else statement that turns stuff off into more IF statements, and other things. Here is my code :
void Update()
{
CauldronDetection();
SpellBookDetection();
}
void CauldronDetection()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.TransformDirection(Vector3.forward), out hit, 5))
{
Debug.DrawRay(Camera.main.transform.position, Camera.main.transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
if (Input.GetKeyDown(KeyCode.E) && hit.collider.tag == "Cauldron" )
{
//Cauldron
if (!cauldronMenuOn)
{
cauldronUI.SetActive(true);
cauldronMenuOn = true;
Cursor.lockState = CursorLockMode.None;
playerScript.canMove = false;
}
if ( cauldronMenuOn)
{
cauldronUI.SetActive(false);
cauldronMenuOn = false;
Cursor.lockState = CursorLockMode.Locked;
playerScript.canMove = true;
}
}
}
}
void SpellBookDetection()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.TransformDirection(Vector3.forward), out hit, 5))
{
Debug.DrawRay(Camera.main.transform.position, Camera.main.transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
if (Input.GetKeyDown(KeyCode.E) && hit.collider.tag == "Book")
{
//Spell Select
if (!selectMenuOn)
{
selectUI.SetActive(true);
selectMenuOn = true;
Cursor.lockState = CursorLockMode.None;
playerScript.canMove = false;
}
if (selectMenuOn)
{
selectUI.SetActive(false);
selectMenuOn = false;
Cursor.lockState = CursorLockMode.Locked;
playerScript.canMove = true;
}
}
}
}
Answer by Bunny83 · Nov 06, 2021 at 11:26 PM
There's no contradition. Your two if statements in line 16 and 23 are check one after the other. When "cauldronMenuOn" is false you would enter the first if statement. However inside that if statement you set cauldronMenuOn to true. So when the first if statement body is finished, the second if statement would be executed since the variable is now true. Instead of your second if statement you can use an "else" between your two bodies.
Though another way would be to get rid of the if statements completely and just do this:
if (Input.GetKeyDown(KeyCode.E) && hit.collider.tag == "Book")
{
selectMenuOn = !selectMenuOn;
selectUI.SetActive(selectMenuOn);
playerScript.canMove = !selectMenuOn;
Cursor.lockState = selectMenuOn?CursorLockMode.None:CursorLockMode.Locked;
}
Your answer
