“If” statement does not work, gameobject with this script destroys any object with any tag and even if i dont press anything. What am I doing wrong?
public class PullScript : MonoBehaviour
{
[SerializeField] private bool pullKeyIsPressed = false;
private void OnTriggerStay(Collider other)
{
if (other.tag == "MoveboxTag" && pullKeyIsPressed);
{
Destroy(other.gameObject);
}
}
private void Update()
{
if (Input.GetKey(KeyCode.S))
{
pullKeyIsPressed = true;
}
if (!Input.GetKey(KeyCode.S))
{
pullKeyIsPressed = false;
}
}
}
The problem is that you have a semicolon after your if() statement, which IS VALID as a result of C# syntax:
if(statement_is_true)
{
Debug.Log("All lines between these curly braces...");
Debug.Log("... are parsed, since this is their given scope.");
}
if(statement_is_true)
Debug.Log("This one-liner can be written on the following line...");
if(statement_is_true) Debug.Log("... or even on the same line.");
Debug.Log("This message is outside the scope of any if statement, so it will always be printed.");
Additionally, scope does not necessarily have obvious prerequisites:
void SomeFunction()
{
int a = 1;
// Enter new scope here
{
int b = 2;
}
a = b; // INVALID - 'b' DOESN'T EXIST OUTSIDE ITS SCOPE!
}
In short, an
if() statement
*without* curly braces for
scope will run the following line of code to completion. In your case, that "following line" ended immediately after your if statement with a semicolon...
if(other.tag == "MoveboxTag" && pullKeyIsPressed) -- > ; <--
… and the scope that followed ran regardless.
Addendum:
For what it’s worth, the content of your Update() function could also be changed to a simple, less-verbose version of itself:
private void Update()
{
pullKeyIsPressed = Input.GetKey(KeyCode.S);
}
Damn, such a stupid mistake i made, thank you! Programming is very interesting.