Sitemap
Simon Pham

Simon Pham

Static Types (Part 2/3): Utility Helper Classes

2 min readMar 12, 2024

--

In today’s blog post, let’s talk about one of the most common uses of static classes — utility helper class.

Press enter or click to view image in full size

What is a utility helper class?

A utility helper class is a class that contains helper methods to streamline and speed up the development process. For example, you can have a utility helper class responsible for updating UI elements like health bars, scores, timers, player stats, etc. Typically, utility helper classes are static, allowing them to be called from any script.

Utility helper class demonstration

To demonstrate this, let’s create a simple utility class called “UtilityHelper” that contains two methods: CreateObject and SetPositionToZero.

public static class UtilityHelper
{
public static void CreateObject()
{
GameObject.CreatePrimitive(PrimitiveType.Cube);
}

public static void SetPositionToZero(GameObject obj)
{
obj.transform.position = Vector3.zero;
}

}

The CreateObject method spawns new cubes and SetPositionToZero, as the name suggests, sets position of a GameObject to the zero position (0,0,0).

Get Simon Pham’s stories in your inbox

Join Medium for free to get updates from this writer.

Next, let’s create a player (which is a red cube) and its script.

Player GameObject
public class Player : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
UtilityHelper.CreateObject();
}

if(Input.GetKeyDown(KeyCode.E))
{
UtilityHelper.SetPositionToZero(this.gameObject);
}
}
}

In the Player script, I have a few lines of code to handle the player inputs. And here’s the result:

As you can see, a new cube was spawned when the Space key was pressed, and the Player GameObject’s position was set to zero when the E key was pressed.

--

--