I try to make a button where GameObjects can be activated or deactivated when clicked on a button or key. In first instance, the objects have to be visible or activated. The code beneath (in italic) this text shows my attempt to do this.
Strange is that the Debug.Log does behaves like it should be, but the regarding the loops it only runs the loop that comes last (in this case Keycode Q = False). It looks like for example that it ignores the if (Input.GetKeyDown(KeyCode.W)) code.
What am I doing wrong?
Thanks in advance,
Louis
public class ShowHide : MonoBehaviour
{
public GameObject [] HideObjects;
// Use this for initialization
void Start()
{
for (int i = 0; i < HideObjects.Length; i++)
HideObjects[i].SetActive(true);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
Debug.Log("Alles aan");
{
for (int i = 0; i < HideObjects.Length; i++)
HideObjects[i].SetActive(true);
}
if (Input.GetKeyDown(KeyCode.Q))
Debug.Log("Alles uit");
{
for (int i = 0; i < HideObjects.Length; i++)
HideObjects[i].SetActive(false);
}
}
}
Basic background:
‘if’ statements only run a single piece of code.
The way to run more than one line of code is by enclosing multiple lines inside the {} braces. These braces group statements and declarations and effectively appears as one piece of code, hence why they are often used with conditionals.
So:
if (condition)
Debug.Log("Test");
//If condition is true, Test, else nothing
Is exactly the same as
if (condition)
{
Debug.Log("Test");
}
//If condition is true, Test, else nothing
However:
if (condition)
Debug.Log("Test");
Debug.Log("Test2");
is actually the same as
if (condition)
{
Debug.Log("Test");
}
Debug.Log("Test2");
//If condition is true, Test, Test2
//else Test2
Your code:
What your code is actually doing is running the debug calls based off the if statement but only that line.
The code within the braces is actually just part of the Update method so your code is effectively:
void Update()
{
//If we are pressing W, debug message
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("Alles aan");
}
//Set all HideObjects to active
for (int i = 0; i < HideObjects.Length; i++)
{
HideObjects[i].SetActive(true);
}
//If we are pressing Q, debug message
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("Alles uit");
}
//Set all HideObjects to inactive
for (int i = 0; i < HideObjects.Length; i++)
{
HideObjects[i].SetActive(false);
}
}
Can you see the mistake now? (edit: Comments added for clarity)
So you are actually running a conditional debug, setting everything to active, running another conditional debug, then setting everything to inactive, every update loop! This is the cause of your debug confusion (In particular why it seemed like pressing Q was working correctly - Debug message (conditional on keypress) and all inactive (happening every frame anyway so it appeared to be working; just the activation appeared to not be working)). Hopefully this background helps you understand conceptually a bit more.