Using Reflections in Update() instead of many IF statements

I was finding it a bit of a bad “code smell” to use so many if statements or even a switch statement. I’m new to C#, but am familiar with language reflection in both scripting languages and languages such as Java, so I dug in a bit and discovered that this can be done in C# as well.

Basically, the idea is that since we know the names of the States and the method names that we call are purposefully named to be similar or identical, that you can programaticaly invoke a method based on it’s name without having to type the name itself into code.

Here’s the snippet:

Take a look at Update() and also note you’d need to have ‘using System’ and ‘using System.Reflection’.

You can actually collapse that line where you’re getting the type and do that all in-line on the next line, but then the parameter line folding could start to get uglier.

1 Like

You can do even better using delegate to get rid of both the enum and the massive Update code. :slightly_smiling_face: