Unity C#: Static
Objective: Create a static helper script allowing an object to change color.
A static declaration can be used for a class, method or variable. A static declaration has some restrictions. A static class cannot inherit MonoBehavior, nor can it be inherited. A static class may contain only static variables and methods. Static variables will not show up in the inspector, unless in debug mode. There can only be a single copy in a project. The benefit is that a static class/method/variable is globally accessible. No need to establish a reference to a static object, because the static object persists in memory and not associated with a specific game object.
An example is shown below for ColorHelper which is a static class with a single static method ChangeColorRandom. Since a static class is never attached to a game object it requires an object to act upon, hence it is a helper method.
A static method is always called from another game object, in this case Player. Observe the simplicity of the script referring to a static class. There is no need to obtain a reference to the static class as it is already available. In the example below the ColorHelper is accessed if the space key is pressed and used to call the ChangeColorRandom() method shown above to change the color of the object.
Frequently, a helper method will contain multiple methods. For example instead of applying a random color the Player could specify the color. This ChangeColor() method requires an addition parameter be passed to the method, the color.
To do this the Player script is modified to allow selection of red, green or blue based upon they keys “R”, “G” or “B” being pressed as shown below, each passing the appropriate color to the ChangeColor() method.
Static methods are easy to use, but are retained in memory indefinitely. Be judicious in their utilization, particularly if memory is limited.