MethodInstructions are a way of calling a method at some time in the future. They can simplify the creation of effects and animation in game development. The DelegateInstruction provides the same functionality for simple cases.
There are a few things to remember when using MethodInstructions:
While MethodInstructions can be manually executed, the easiest way to use them is to add them to an IInstructable that is being managed such as a Sprite. This way you don't have to manually watch for instructions to call them. The manager takes care of it for you!
MethodInstructions cannot call static methods. You'll see in the following example that SpriteManager.RemoveSprite needs to be wrapped in another method. Another alternative is to create a StaticMethodInstruction.
The following code creates an effect that could be used for explosions when the user presses the space bar. The code does the following things:
These instructions are added to the InstructionManager since there is no object around to "own" these Instructions.
When a Sprite is created its properties are set and another MethodInstruction is created to remove the Sprite after 1 second.
Add the following using statement:
Add the following code to Update:
Add the two methods which will be used as MethodInstructions:
The third argument to the MethodInstruction constructor is an argument list. This argument list is an object array (object[]) which stores the arguments.
For example, if you were calling a function called SetSpriteScaleAtTime which had the following signature:
You may create an argument list as follows:
MethodInstructions attempt to call methods using reflection. They obtain the method to call using the name of the method. However, if the method that you want to call has multiple overloads then you will need to supply a MethodInfo to tell which version of the method you want to call.
For example, let's say you are working with an AxisAlignedRectangle instance and you want to call CollideAgainst using a MethodInstruction. The following code can be used to call CollideAgainst against a Circle:
Did this article leave any questions unanswered? Post any question in our forums for a rapid response.