Utility Classes In Unity

Utility classes/Helper Classes

PieceofPhie
2 min readMay 14, 2022

A Static class that allows you to use methods across other scripts throughout your project.

Example

I have a player, A ground cube to stand on, and Four walls to collide with.

The Player will change to a random color if I press space.

The player and wall will swap colors with each other if they collide.

The player has a ,’Player’ tag and all four walls have a ,’Wall’ tag.

Demonstration

Scripts

Two Scripts were created; ColorUtilityScript and PlayerScript

ColorUtilityScript

A Public static class with two public static methods with game object parameters. The methods get the renderer components of the passed game objects to access their material colors.

Having it set as a public static class allows communication bettween all other scripts without needing to ,’hook’ them up. Ie: .GetComponents<>

ColorSwap first stores the player’s and wall color in a local variable(s) PlayerColor and WallColor.

Then assigns the local variables to the opposite game objects that were passed in the method’s parameters. PlayerColor to Wall and vice versa.

These methods will be called from the player script.

PlayerScript

RandomColor method from the ColorUtilityScript is called when spacebar is pressed.

ColorSwap is called with the player has collided with a gameobject with a tag of ,’Wall’.

Conclusion

I can use a Helper Class to avoid rewriting methods across multiple scripts. This is useful for methods that will be frequently called across multiple scripts

note

Since Helper/Utility classes are static, all information will be indefinitely stored until the program is closed. Watch out.

--

--