Creating A Singleton DataCtrl Class

A free video tutorial from AbleAppsDev .
Teaching Unity Game Dev, Web Dev, Python, Machine Learning
Rating: 4.4 out of 5Instructor rating
1 course
32,141 students
Creating A Singleton DataCtrl Class

Lecture description

You will create a DataCtrl Singleton which will be in charge of loading/saving data. In this video, you will create the singleton and in the next video the loading/saving functionality.

Learn more from the full course

Unity & C# - Build A Complete 2D Mobile Platformer Game

Learn How to Develop a Complete 2D Mobile Platformer Game in Unity C# From Start to Launch in Google Play Store

19:25:17 of on-demand video • Updated April 2022

Create a mobile platformer from scratch to launch in Google Play Store
Easily monetize your game with AdMob banner and interstitial ads
Master Sixteen Popular Platformer Game Mechanics like Background Parallax, Breakable Crates, Coin Pickup Effects and more
Create an animated 2D game character with behaviors like left/right movement, jump, fire bullets, pickup coins, crush enemies, water splash and more
Design/Update levels 10x faster using my Unity asset: Level Designer
Implement Level Locking/Unlocking with awarded stars showing below level buttons in the Level Select Menu
Create and work with Prefabs
Use the components of Unity 2d Physics like Rigidbody2d
Work with Colliders and Collision Detection
Understand best practices of Level Design
Create Your Own 2D Player Controller
Easily create and work with a custom binary database file
Program useful gameobjects like GameController, AdsController, DataController etc using Singleton pattern
Program enemy characters with basic AI
Create a challenging boss battle
Build & test your game on an Android device
Deploy your finished game to Google Play store
Best practices of working within Unity editor and C# scripting
Take practice quizzes after every section
English [Auto]
In this video, I want to show you how to use a Singleton class for managing your data operations using a game object called data controller. All of this sounds complex. So let's get started by first watching what the problem we're trying to solve. The problem is, by default, a game object that you create in a certain scene remains in that scene. And when you change the scene, it gets destroyed. Right. It does not persist across multiple scenes. Now, when the game begins, say you have the menu screen as the Start-Up screen. If you have some coding for accessing database items in this scene and you change to the level select screen. So the coding for database is gone. You'll have to do the coding again for a level select access database items. So here's the problem. You're creating code for accessing database items in every scene. You may say that's not a problem because I only have two scenes. OK, but what happens if you have more than one or two scenes? It's very common in mobile platforms to have about 50, 60, 70, 100 scenes. So you'll end up creating database code for all of these levels. That's not good. It violates a common software engineering principle called D-R. Why? Or don't repeat yourself. OK, imagine if you go beyond the complexity of 50 levels, you have 100, 150 levels. Would you want to do the database coding for each and every scene? Well, the solution is to create a data controller game object, which persists across scenes. All right. It doesn't get destroyed when you change from one scene to the other scene. So in the menu scene, say you create a data controller, a game object, which has the data controller script change to the levels of 16. And this data controller follows you along. OK, that's the good thing. You change to level one. You play the game data controllers available in level one. It provides you data access. You finish level one, come back to level. Select data controller keeps following you. You go back to the menu. Data controller is there to give you access to the database. So first thing, it solves the problem of redundant code. You do coding in one place and that's it. So this is an efficient way of managing your database operations. Right. Let's dive right in and see how to get this implemented. The first step is you create a game object called data controller in the startup scene of your game, then you're going to add the data controller script to it. And what do I mean by the startup scene? That is the first scene which is shown to the player when your game begins. Right. It's not the split screen, although you can do it there. But in this video or in this course, want to use the menu screen to create the data controller. Right. So let's dive right in and get this first step implemented. The first step is looking at these scenes folder under the assets folder and Double-Click the menu scene to open it. Then in this menu scene, you have the menu controller. When you did the section on creating the menu, you learned one technique by using the menu controller right in this video, I'm going to show you another technique. So we're going to delete the menu controller instead, right? Click and create empty and rename this game. Object to the controller. This data controller will have a script. So click add component type and data controller hit return two times and you'll notice a data controller script has been added and now is the time to see this problem in action. The problem is when you have a game object in a particular scene, in this case, the menu, when you change the scene, the game object gets destroyed. Let's have a look at this problem in action. Let's begin with the menu scene, which has the data controller game object, this game object has the data controller script for a moment. Let's assume that the data controller script provides you with methods to access the database. So far, so good. Let's go to the game mode and see what happens. Well, the data controller is right there. It's going to provide you with all the database access in this particular scene. But what happens when I change the scene to level select click play and let's see if we have the data controller. Whoa, the controller is not there. You can search for it right here, type in data and there it's gone. Right. That's the problem we're trying to solve because you've written the code for database access in the menu scene in this scene. If you need access to the database, well, there's no data controller anymore, so you'll have to write all the code one more time. Right? That's not good if I go back. And here's the data controller again, and it brings back the database access code. It would be great if this data controller starts to follow me into the level select screen, into the level one screen and so on and so forth to any scene where I need database access. Right. So we're trying to solve this problem. Let's see how to get it done. Double-Click, this data controller field to edit the script. Let's begin the script by adding a summary, this will be a Singleton class for creating a persistent data control game object, and this will help you in creating a centralized database access code. So this completes step number one, we created a game object called data controller in the startup scene, which is the menu in this case, and then we added a data controller script to it. The second step is indeed a controller script, we're going to create a variable called Instant's and it's going to be of type data controller, it's access modifiers. Can it be public? And it's going to be a static variable initialized to a value of no. Let's see how to get this done. Indeed, a control group, let's right public static data controller instance equals not this one line is creating a variable called instance of type data controller. It's got the axis modifiers, public static and it's being initialized to a value of not. So with this, we have completed step number two in step number three, we're going to write in if lock and check if the instance variable is now, if it's found, we know we're going to assign equals this and we're going right. Don't destroy, onload and pass in this current game object. If not, then we're going to destroy the current game object. Using this logic, you're going to make sure that the data controller persists across different scenes and only one instance of data controller is available. Let's get onto the scripting. And as I write the script, I'll explain each and every line. We're going to start writing the code for creating a singleton in the awake method. Why a week and why not the start? This is a very good question and here's the answer. In the unity documentation, have a look at execution order of event functions. You'll notice that there's a cycle or a life cycle in which the model behavior methods are called in a certain order. A week is called before start. You may still be wondering, but how is it going to help you? Here's how it's going to help you. The data controller needs to initialize itself, right? It needs to do some startup coding so that it can become a singleton. Right. Normally, if you do it in the start method, imagine if Button also wants access to certain database elements and you've written the code in the START method. Now there are two stark methods. And when you go to the play mode, unity starts to execute all the scripts at the same time. And then what's going to happen is both start methods are being called. At the same time there's going to be a problem. Why? Because at the time when data controller is initializing itself and it's trying to become a singleton class, one player is asking for database access. Well, that cannot happen because data controller is not ready. There's going to be a problem. So the simple solution is to write all the initialization code for data controller in the awake method. A week is called before start. No problem. By the time a call from button play comes, data controller is ready because all of the coding was in the awake. Awake was called before start. Everything is good. So back in the script in the Awake Method, we're going to write the first F block. This if block is going to check if the instance variable is null means it doesn't point to any game object in that case. Go ahead, assign a reference to this game, object to the controller game object and store it in the instance variable. After doing this, don't destroy this game object onload onload means when changing scenes. Right, so this one method will do the trick for you. Time to test. Here's the menu scene. Let's go to play mode and notice something interesting happens now the data controller has something called Don't Destroy OnLoad and here's the data controller. OK, this looks interesting, but the question is, is it going to follow me in the level select menu? So I pressed play button and there this is awesome because the data controller decided to follow me and this is working. OK, well, before I get excited about it, if I go back to the menu. Here's something interesting, you have one instance of data controller, but if I expand the menu there, there's a bit of a problem. The data controller has two instances which will cost conflicts. Right. If despondently tries to get access to some data element, which of the data controllers should provide access? There's going to be a problem. So a simple fixes. In the awake method below the if blocked, let's write else one line destroy game object, so this if block will ensure that only one instance is created and it's not destroyed, it starts to persist across scenes. And if any attempt is made to create another instance off the data controller, it is destroyed. Right? This if an X block will create a persistent game object called the controller, that's going to be there with you during all the scenes. So let's have a look. Here's the menu scene. Let's go to promote. And there you've got one instance of data controller, I click the button and we have a data controller which is following us from the menu, we expand World one. There's only one instance. We go back to the menu, we expand the menu and their problem result. You have only one instance of data controller. So as you can see, if I keep going to different scenes because of the coding you just did, data controller will keep following you from one scene to the other scene. Right. And if you have a question that does data controller is going to be destroyed or not? Yes. When you quit the game, it's going to be destroyed. Right. It persists or it stays alive. As long as you have the game running, it's going to follow you from scene to scene. And that's about it. When you quit the game, the data controller is destroyed. So there you have it, a Singleton data controller class, which is going to follow you from seeing the scene. And it's going to provide you data access. But we haven't written any code for doing the data access. Join me in the next video and I'll show you how to load and save data using this data controller. All right. I'll see you there.