Unity Update is ignoring the GetKey part of my statement!?
I can't understand this at all. Now this code isnt working but its very strange. In all of the if statements I have stated that a key must be pressed and yet as soon as a run my game it runs the first if statement without me touching the keyboard. Could someone please explain how this is happening? Thanks in advance.
using UnityEngine;
using System.Collections;
public class Indicator : MonoBehaviour
{
public int indicator;
public Renderer indicatorLeft;
public Renderer indicatorRight;
void Start()
{
indicator = 0;
}
void Update()
{
if (indicator == 0 || indicator == 2 && Input.GetKeyDown(KeyCode.Q))
{
indicator = 1;
//This part turns on the left indicator.
indicatorLeft.enabled = true;
GameObject.FindWithTag("IndicatorLeft").GetComponent<AudioSource>().mute = false;
print("Indicating Left");
//This part turns off the right indicator.
indicatorRight.enabled = false;
GameObject.FindWithTag("IndicatorRight").GetComponent<AudioSource>().mute = true;
print("Right Indicator Off");
}
if (indicator == 0 || indicator == 1 && Input.GetKeyDown(KeyCode.E))
{
indicator = 2;
//This part turns on the right indicator.
indicatorRight.enabled = true;
GameObject.FindWithTag("IndicatorRight").GetComponent<AudioSource>().mute = false;
print("Indicating Left");
//This part turns off the left indicator.
indicatorLeft.enabled = false;
GameObject.FindWithTag("IndicatorLeft").GetComponent<AudioSource>().mute = true;
print("Indicating Right");
}
if (indicator == 2 && Input.GetKeyDown(KeyCode.E))
{
indicator = 0;
//This part turns off the right indicator.
indicatorRight.enabled = false;
GameObject.FindWithTag("IndicatorRight").GetComponent<AudioSource>().mute = true;
print("Right Indicator Off");
}
if (indicator == 1 && Input.GetKeyDown(KeyCode.Q))
{
indicator = 0;
//This part turns off the left indicator.
indicatorLeft.enabled = false;
GameObject.FindWithTag("IndicatorLeft").GetComponent<AudioSource>().mute = true;
print("Left Indicator Off");
}
}
}
Answer by Pengocat · Dec 16, 2016 at 12:15 AM
I guess you want to place the Input condition before the indicator check otherwise the Input will never be evalutated if the indicator condition is true.
if (Input.GetKeyDown(KeyCode.Q) && indicator == 0 || indicator == 2 )
Answer by Havax · Dec 16, 2016 at 12:47 AM
You are saying
(indicator == 0 || indicator == 2 && Input.GetKeyDown(KeyCode.Q))
As in "Do this if (Indicator == 0) OR (Indicator == 2 and Input.GetKeyDown(KeyCode.Q)))
That AND has no effect on the "Indicator == 0" because there is an OR statement inbetween.
Use:
((indicator == 0 || indicator == 2) && Input.GetKeyDown(KeyCode.Q))