Yes, there’s a problem with the if and else statements.
Variables in C# are scoped local to the code block they’re declared in. A variable is declared where you give its type and name. So in your first code above, a GameObject variable called “hazard” comes into being where it is declared on line 3, and disappears at the end of the code block on line 5. Another GameObject variable, coincidentally also called “hazard”, comes into being on line 7 and disappears on line 8. And then you try to use something called “hazard” on line 12, but there is no such identifier declared. The hazards on line 3 and 7 are not around anymore.
So to do what you want, you’d need to declare your GameObject hazard only once, before the if-statement. Then you can assign to it (without redeclaring it!) in your if and else blocks, and it will still exist afterwards, all the way until the end of the method.
and am now getting “A local variable hazard can not be declared in this scope because it would give a different meaning to ‘hazard’ which is already used in ‘parent or current scope’ to denote something else”
and that error appears for for the if and else
The error is exactly right. Read it carefully; it’s telling you exactly what is wrong (especially if you pay attention to the line number it’s talking about).
Also read carefully my advice: “Then you can assign to it (without redeclaring it!) in your if and else blocks”.
Both the error message, and my instructions, are telling you not to declare “hazard” in your if and else blocks. So, quit doing that.
Remember, a variable is declared where you give its type and name. The type here is “GameObject”. If you say “GameObject hazard” you are declaring a new variable of type GameObject, called hazard.
No worries, we’ve all done stuff like that. Fortunately, C#'s error messages are really good — the best of any development environment I’ve ever used. 95% of the time they tell you exactly what is wrong (and half the time, they make a sensible suggestion on how to fix it too!).