I use switch to choose weapon shoot mechanic. Problem that i not want to check enum value each time when i do shot. I need to check only once (on awake for example) what option i need. Maybe switch not best for this situation, so i listen all possible suggestions.
public enum Shoot_Type
{
BEAM, SHELL
}
public Shoot_Type Type_Of_Shoot;
void Update()
{
if (Input.GetButtonDown("Fire"))
switch (Type_Of_Shoot)
{
case Shoot_Type.BEAM:
Beam_Mechanic();
break;
case Shoot_Type.SHELL:
Shell_Mechanic();
break;
}
}
At the moment there’s not much to optimize. The type will only be evaluated when the key is pressed down and there aren’t many options. Switch-case and if statements are generally pretty performant.
However, there are other more elegant ways of dealing with such a situation, especially when the behaviour gets more complex and the code starts to get lengthy. You could have a look into delegates / events. There are already nice quick-to-use wrapper such as Action (or the generic version) and Func (which returns a value and can have a few parameters as well).
These types can encapsulate different methods with the same signature.
The advantage would be a much shorter and cleaner code (1 line, if you do null-checks, 2 lines) in Update and additionally no comparison (which is what you’ve asked for), only once each time you switch the type of fire-mechanic and that can be handled in a different method which is not called frequently.
(A similar approach is based on a class-hierarchy or interface system, but that’s probably too much for just a single method.)