The Singleton Pattern

Yesterday, we looked at creating Manager classes, but ultimately we only ever want to have one instance of each. To ensure this, we can make use of the Singleton design pattern. The Singleton pattern allows us to restrict a class to one instance.

Much like yesterday, we can create a private Instance variable, and then through the use of a property, we can create a public reference to retrieve functions of code. In this case, returning the private Instance variable. At this point though, we need to check if the Instance already exists, if it does not, we can Debug an error message, or create a new GameObject and attach the script. This is an example of lazy instantiation, which can provide a quick and easy solution, but can introduce the downfall of stored variables that need to be assigned in the inspector.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store