if else statement

I am using an if else statement to calculate the players accuracy from the targets he/she manages to hit as shown below very basically. if the player hits barrel1 then variable br1 is updated in a different gameobject holding the values to calculate the accuracy. A problem I’m having is that even when the player hits the first barrel both variables br1 and br miss are updated. I think the first and second if statements are seperated so i would like to use and if else if statement but doesn’t seem to work. any ideas?

if(hit.collider.gameObject.tag=="barrel") { GameDataScript gamedatascript= gameData.GetComponent<GameDataScript>(); gamedatascript.br1+=1; } if(hit.collider.gameObject.name=="barrel2") { GameDataScript gamedatascript= gameData.GetComponent<GameDataScript>(); gamedatascript.br2+=1; } else { GameObject gameData = GameObject.Find("GameData"); GameDataScript gamedatascript= gameData.GetComponent<GameDataScript>(); gamedatascript.brmiss+=1; } }

1 Like

insert an else if query instead of a single if.

example:

if(hit.collider.gameObject.tag=="barrel")
// do stuff with your br1 variable
else if (hit.collider.gameObject.tag=="barrel2")
// do stuff with br2 variable
else
// do stuff with brmiss var
1 Like

thanks mate i was using “elseif” didn’t even think of putting a space between them!

1 Like

One word of caution though, if the “do stuff” sections consist of more than one line of code, you’ll need to group them with braces. In fact, even if they are only one line, you can still use the braces - they won’t hurt anything.

So, like this:

if (hit.collider.gameObject.tag == "barrel")
{
   // do stuff with your br1 variable
   // do more stuff
}
else if (hit.collider.gameObject.tag == "barrel2")
{
   // do stuff with br2 variable
   // do more stuff
}
else
{
   // do stuff with brmiss var
   // do more stuff
}
1 Like

nice one cheers bud

1 Like