Have you ever coded conditional rules like:
When (Variable = 1) <do something> When (Variable = 2) <do something else> When (Variable = 3) <do something different>
only to forget at some point what having the variable equal 1, 2, or 3 meant?
Here I’ll explain how “constants” can be used to make the code easier to read. This will help prevent bugs and make the code easier for everyone to understand. I’ll demonstrate the use of “constants” through a practical example of a custom rule to watch the pressed state of an object.
Foreword: Constants is in quotes above as Hopscotch doesn’t really have constants, but we’re going to use variables to replicate the functionality of constants.
Ok, so what do I mean by using constants? A constant is simply a value that’s defined and not changed. Then in code you can use the constant and know what it means based on the name and don’t have to worry about the actual value. For example, instead of
we can replace the values with constants (Note the naming convention. I like to use a prefix like “#” so I know the variable is intended to be used as a constant and I shouldn’t arbitrarily change it)
Now, anyone looking at the code can easily tell what the events are for! And you don’t even need to know what the values of the constant are!
Ok, so before the code above will work we have to define the constants. I’ll show you that in a minute, but some of you may being saying, "Hold on! All variables start out with a value of 0, so all of the events are effectively
as the project starts and therefore all of these rules will run at the beginning until the constants get assigned their values"
That’s absolutely true. So we have to define the constants in a very specific way due to the order in which the Hopscotch Player executes the code blocks.
- The constants have to be defined in the 1st object (I like to name this object “Main” because it gets executed first and so I know to keep it 1st in the order of objects)
- Each constant has to be defined in its own When Game Starts rule
Again, it’s important that each constant is prefixed with #. This will prevent confusion later on. #NotPressed = 0 didn’t have to be defined, but this is a good idea just to be explicit.
That’s it for the basics of using constants! To complete my example, I coded this custom rule (Watch Pressed State)
That custom rule can be added to any object where you want to do something when the object ‘Is Released’, ‘Is Not Pressed’, or ‘Is Pressed’ (obviously the native Is Pressed could be used instead). After the Watch Pressed State custom rule you just add a 2nd rule, referring to the desired constant, with the code for that object.
I just made them all “spin” in the example project below, but each object would typically have different code.
Here’s a link to the example project (if the link doesn’t work, search Hopscotch for “Watch Pressed State” by ThinBuffaloSr)
If you made it this far, thanks for reading and I hope this tutorial was helpful!