DEV Community

drinkingWater
drinkingWater

Posted on

Singleton in Unreal Engine

Singleton pattern is a very important pattern for storing states in a game and keep them persistent between levels. Also, to share data between at some point.
*Problem: * In a game I am currently working on, there are some actors called trash. After a certain amount delay if these items aren't pick up, they destroy and increase pollution factor in the world. Now the pollution factor has to be accessed by every trash to send the event if they are destroyed. Also, if scene changes, the pollution factor won't change.

**Solution: **Make a singleton class where all the variables which have to be persistent between levels or scenes.

**Challange: **In unity I used a lot of DontdestroyOnLoad to make a lot of persistent object which is recommended. I could keep multiple singleton classes for different mechanism or work. In unreal however you can work with only one singleton class which is called "Game Instance" here.

**My Approach: **Firstly created a Game Instance from blueprint menu. It's like any other blueprint.

Image description

In the project settings I changed the default instance with the new one I created.

Image description

In the Game Instance blueprint I created a custom event which will count pollution factor within. For that I also added a variable to store the pollution factor. And also, why not the life span of the trashes. That way I can change the life span for every trash at once. Also, how much trash to spawn at each time.

Image description

In the trash I call the event and update the trash count. For that we Get the game instance and cast it to the newly made game instance.

Image description

This is how I am implementing singleton for now. This does solve all the singleton related problem for me. But the bad habit of having multiple singleton classes in Unity does irritate me xD.

Top comments (0)