- Home /
The question is answered, right answer was accepted
If statement not catching certain parameters?
The mechanic I'm trying to work with involves simply recognizing that a block has a certain color and pressing the corresponding button (Shoot vs NoShoot). If you press shoot on a noshoot target, you don't get a score, and vice versa. However, if I press spam the NoShoot button constantly, sometimes it will give the player a point even when the target is a Shoot. Again, this is not happening on every wrong input, and it never happens when pressing the Shoot button repeatedly.
I'm assuming it's a problem with using the Update function to make all this happen, but it may just be poor coding. Any ideas?
function Update ()
{
if(GameObject.Find("Shoot(Clone)"))
{
if(Input.GetButtonDown("Shoot"))
{
Destroy(GameObject.Find("Shoot(Clone)"));
print("GOOD JOB!");
score++;
Spawn();
}
if(Input.GetButtonDown("NoShoot"))
{
Destroy(GameObject.Find("Shoot(Clone)"));
print("WRONG");
Spawn();
}
}
if(GameObject.Find("NoShoot(Clone)"))
{
if(Input.GetButtonDown("Shoot"))
{
Destroy(GameObject.Find("NoShoot(Clone)"));
print("WRONG");
Spawn();
}
if(Input.GetButtonDown("NoShoot"))
{
Destroy(GameObject.Find("NoShoot(Clone)"));
print("GOOD JOB!");
score++;
Spawn();
}
}
}
Answer by Jamora · Jul 13, 2013 at 07:12 PM
Your code doesn't actually check if the mouse cursor is on the gameobjects. The only thing checked is whether or not they exist in the scene, as GameObject.Find() will return null if nothing is found. (Null will always return false when checked in an if.) At some point in your game, you probably have both types of objects in the scene, so the behaviour you described happens.
That beign said, Doing GameObject.Find() repeatedly will kill your framerate, especially if done twice every frame. I suggest you look into using OnMouseDown on your objects that need to be clickable.
Expanding on this, you can set a variable equal to GameObject.Find() outside of Update() so that you can use that variable inside of Update() without killing your framerate.
Answer by James U · Jul 13, 2013 at 06:28 PM
I'm not certain, but I think the problem is with your if statements.
if(GameObject.Find("Shoot(Clone)"))
This (I think) doesn't make sense because if statements check for true or false values. GameObject.Find() returns a GameObject, and not 1 or 0 (true or false).