{"id":849,"date":"2022-12-10T05:57:11","date_gmt":"2022-12-10T05:57:11","guid":{"rendered":"https:\/\/globalgoodplay.com\/?p=849"},"modified":"2023-04-13T09:14:00","modified_gmt":"2023-04-13T09:14:00","slug":"singletons-in-unity-how-to-implement-them-the-right-way","status":"publish","type":"post","link":"https:\/\/globalgoodplay.com\/?p=849","title":{"rendered":"Singletons In Unity \u2013 How To Implement Them The Right Way"},"content":{"rendered":"<div data-elementor-type=\"wp-post\" data-elementor-id=\"34592\" class=\"elementor elementor-34592\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-51f8453 elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"51f8453\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-63b23c3\" data-id=\"63b23c3\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-38774d3 elementor-widget elementor-widget-text-editor\" data-id=\"38774d3\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Singleton is a design pattern that is used as a container which holds values that can be globally accessible across the whole project.<\/p>\n<p>Singletons are very useful because they can transfer game data from scene to scene without the need to save and load data in the background.<\/p>\n<p>There\u2019s also a debate amongst game programmers should you be using the singleton pattern at all because if your game gets too large then it will be hard to manage and so on.<\/p>\n<p>We don\u2019t believe that is case because you\u2019re not going to have 100 singletons in a project. You\u2019re going to have one or a couple of them and they save you a lot of time because they provide an easy way for classes to communicate between each other.<\/p>\n<p>Before we start, this tutorials is for beginners as well as intermediate and advanced developers.<\/p>\n<p>We\u2019ll cover everything from how to create a simple singleton to more complex operations you can perform with it so both beginners and advanced developers will benefit.<\/p>\n<p>And you can always use the table of content on the left side to navigate the post and learn what you want.<\/p>\n<p>Also, we do expect beginners who follow this post to know the basics of Unity like creating a script, attaching it on a game object, knowing how a class works and so on as we don\u2019t plan to cover the complete beginner stuff.<\/p>\n<p>But if you are a complete beginner, you can start learning by clicking on the link below.<\/p>\n<p>C# Programming In Unity \u2013 Introduction To Variables<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-9a2d1c3 elementor-widget elementor-widget-template\" data-id=\"9a2d1c3\" data-element_type=\"widget\" data-widget_type=\"template.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-template\">\n<div data-elementor-type=\"section\" data-elementor-id=\"31169\" class=\"elementor elementor-31169\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7eaceb00 elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"7eaceb00\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7542c05a\" data-id=\"7542c05a\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-7a156fc9 elementor-widget elementor-widget-ucaddon_ue_random_image\" data-id=\"7a156fc9\" data-element_type=\"widget\" data-widget_type=\"ucaddon_ue_random_image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t<!-- start Random Image - Middle --><\/p>\n<style type=\"text\/css\">\/* widget: Random Image - Middle *\/<\/p>\n<p>#uc_ue_random_image_elementor264113<br \/>\n{<br \/>\n  display:flex;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor264113 .ue-image-item<br \/>\n{<br \/>\n  display:block;<br \/>\n  transition:0.3s;<br \/>\n  width:100%;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor264113 .ue-image-link<br \/>\n{<br \/>\n  display:block;<br \/>\n  color: unset;<br \/>\n}<\/p>\n<\/style>\n<div id=\"uc_ue_random_image_elementor264113\" class=\"ue-random-image\" data-debug=\"false\" data-editor=\"no\">\n<div class=\"ue-image\">\n<div class=\"ue-image-box\">\n<p>      <img decoding=\"async\" class=\"ue-image-item\" src=\"\"><\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!-- end Random Image - Middle --><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-8861535 elementor-widget elementor-widget-heading\" data-id=\"8861535\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">How To Create A Singleton?<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-ced0f04 elementor-widget elementor-widget-text-editor\" data-id=\"ced0f04\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>As we already mentioned, a singleton is accessible globally, and it also needs to exist only once e.g. only one copy of the singleton can exist in the game.<\/p>\n<p>Of course, this is referring to one copy of the singleton with one purpose e.g. only one copy of a the TagManager singleton which holds all the strings you\u2019ll use in the game, one copy of the AudioPlayer singleton which plays the audio sounds in the game and so on.<\/p>\n<p>The code to create a singleton looks like this:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-95557f6 elementor-widget elementor-widget-code-highlight\" data-id=\"95557f6\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class Singleton : MonoBehaviour\n{\n    public static Singleton instance;\n\n    private void Awake()\n    {\n        if (instance == null)\n            instance = this;\n    }\n\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-87fc352 elementor-widget elementor-widget-text-editor\" data-id=\"87fc352\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The instance declared on line 5 is the instance of the class itself. Because we want to access it globally we need to make it static since static variables can be called from any class.<\/p>\n<p>If you don\u2019t know what are static classes you can learn about them here: Static Classes In Unity<\/p>\n<p>On line 9 we are testing if the instance is equal to null meaning we don\u2019t have a reference to the instance variable.<\/p>\n<p>And if that is the case we set the instance to be equal to this which refers to the class holding the script where the keyword this is used \u2013 in this case the Singleton class.<\/p>\n<p>Now for the sake of example, let\u2019s image this Singleton class has a score variable that we\u2019ll use to display score in the console when a button is pressed:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-a08e735 elementor-widget elementor-widget-code-highlight\" data-id=\"a08e735\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>[HideInInspector]\n    public int score;<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-aaddd68 elementor-widget elementor-widget-text-editor\" data-id=\"aaddd68\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Here we have two scripts each with one function. Each function is going to add either 1 or 2 to the current value of the score variable and print it in the console:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-677ad1f elementor-widget elementor-widget-code-highlight\" data-id=\"677ad1f\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class AddOneToScore : MonoBehaviour\n{\n    public void AddToScore()\n    {\n        Singleton.instance.score++;\n        Debug.Log(\"The Score Is: \" + Singleton.instance.score);\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4a1043a elementor-widget elementor-widget-code-highlight\" data-id=\"4a1043a\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class AddTwoToScore : MonoBehaviour\n{\n    public void AddToScore()\n    {\n        Singleton.instance.score += 2;\n        Debug.Log(\"The Score Is: \" + Singleton.instance.score);\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-0e07603 elementor-widget elementor-widget-text-editor\" data-id=\"0e07603\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>These scripts are attached on 2 game objects which are attached on appropriate buttons that we\u2019ll press to increase the score value:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-74540fe elementor-aspect-ratio-169 elementor-widget elementor-widget-video\" data-id=\"74540fe\" data-element_type=\"widget\" data-settings=\"{\" youtube_url\":\"https:=\"\" youtu.be=\"\" omcrdhx_axu\",\"video_type\":\"youtube\",\"controls\":\"yes\",\"aspect_ratio\":\"169\"}\"=\"\" data-widget_type=\"video.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-wrapper elementor-fit-aspect-ratio elementor-open-inline\">\n<div class=\"elementor-video\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4ac47b3 elementor-widget elementor-widget-text-editor\" data-id=\"4ac47b3\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>As you saw, depending on which button we pressed, we added either 1 or 2 to the score variable in the Singleton class and we printed that value.<\/p>\n<p>One thing to note is, the score value was persistent across the two classes. And this is the main purpose of the Singleton pattern \u2013 allowing easy global access to variables between classes.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-dfe3ab1 elementor-widget elementor-widget-heading\" data-id=\"dfe3ab1\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">The Problem With The Current Singleton Setup<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-ec4f987 elementor-widget elementor-widget-text-editor\" data-id=\"ec4f987\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The current setup we have is actually not a singleton.&nbsp;<\/p>\n<p>How?<\/p>\n<p>Because we can have another game object with the same Singleton script attached on it and both will stay in the game:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-8ca5577 elementor-widget elementor-widget-image\" data-id=\"8ca5577\" data-element_type=\"widget\" data-widget_type=\"image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img decoding=\"async\" src=\"https:\/\/glossingdress.com\/lib\/img\/all\/551\/1b072c2e0b419c816bbbf764e13a1f60d1688bdb7f0c0244e4c736c3cc2a7755\/1dfa07a8226c38936e9f594e7792d89eab4700ee9c303ac8f5ca73bcc03e8c98.jpeg\" title=\"Singletons In Unity \u2013 1\" alt=\"Singletons In Unity - 1\" loading=\"lazy\"><\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-ae20544 elementor-widget elementor-widget-text-editor\" data-id=\"ae20544\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>And since the goal of the Singleton is to have only one instance or one copy of the object we need to destroy the other.<\/p>\n<p>To do that, we need to add the following code:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-9af47c9 elementor-widget elementor-widget-code-highlight\" data-id=\"9af47c9\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class Singleton : MonoBehaviour\n{\n    public static Singleton instance;\n\n    [HideInInspector]\n    public int score;\n\n    private void Awake()\n    {\n        if (instance == null)\n            instance = this;\n        else\n            Destroy(gameObject);\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-d27d4a1 elementor-widget elementor-widget-text-editor\" data-id=\"d27d4a1\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>In the first Singleton example we saw, we only performed the check on line 12 to see if the instance is equal to null then we set the instance to be equal to this.<\/p>\n<p>Here we have the else condition on line 14 which will destroy the game object which currently holds this script in case the instance is not equal to null.<\/p>\n<p>This means, if we have two copies of the singleton in one scene, one will be destroyed:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-8c06054 elementor-aspect-ratio-169 elementor-widget elementor-widget-video\" data-id=\"8c06054\" data-element_type=\"widget\" data-settings=\"{\" youtube_url\":\"https:=\"\" youtu.be=\"\" sav5gou27ja\",\"video_type\":\"youtube\",\"controls\":\"yes\",\"aspect_ratio\":\"169\"}\"=\"\" data-widget_type=\"video.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-wrapper elementor-fit-aspect-ratio elementor-open-inline\">\n<div class=\"elementor-video\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-a62261d elementor-widget elementor-widget-text-editor\" data-id=\"a62261d\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>This is how we make sure there\u2019s only one copy of the Singleton class in the game.<\/p>\n<p>But we still have one more problem and that is, if we load another scene, we will lose the Singleton:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4ea391e elementor-aspect-ratio-169 elementor-widget elementor-widget-video\" data-id=\"4ea391e\" data-element_type=\"widget\" data-settings=\"{\" youtube_url\":\"https:=\"\" youtu.be=\"\" zf7rnid6wfs\",\"video_type\":\"youtube\",\"controls\":\"yes\",\"aspect_ratio\":\"169\"}\"=\"\" data-widget_type=\"video.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-wrapper elementor-fit-aspect-ratio elementor-open-inline\">\n<div class=\"elementor-video\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-931f7df elementor-widget elementor-widget-text-editor\" data-id=\"931f7df\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>While we have a reference to the Singleton in Scene 1, when we load Scene 2 we saw no trace of the Singleton object.<\/p>\n<p>The Singleton object needs to be persistent across scenes because that\u2019s how we carry data from one scene to another.<\/p>\n<p>To do that, we just need to add one final line of code:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-2117a24 elementor-widget elementor-widget-code-highlight\" data-id=\"2117a24\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class Singleton : MonoBehaviour\n{\n    public static Singleton instance;\n\n    [HideInInspector]\n    public int score;\n\n    private void Awake()\n    {\n        CreateSingleton();\n    }\n\n    void CreateSingleton()\n    {\n        if (instance == null)\n            instance = this;\n        else\n            Destroy(gameObject);\n\n        DontDestroyOnLoad(gameObject);\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-3c38091 elementor-widget elementor-widget-template\" data-id=\"3c38091\" data-element_type=\"widget\" data-widget_type=\"template.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-template\">\n<div data-elementor-type=\"section\" data-elementor-id=\"31169\" class=\"elementor elementor-31169\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7eaceb00 elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"7eaceb00\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7542c05a\" data-id=\"7542c05a\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-7a156fc9 elementor-widget elementor-widget-ucaddon_ue_random_image\" data-id=\"7a156fc9\" data-element_type=\"widget\" data-widget_type=\"ucaddon_ue_random_image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t<!-- start Random Image - Middle --><\/p>\n<style type=\"text\/css\">\/* widget: Random Image - Middle *\/<\/p>\n<p>#uc_ue_random_image_elementor273898<br \/>\n{<br \/>\n  display:flex;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor273898 .ue-image-item<br \/>\n{<br \/>\n  display:block;<br \/>\n  transition:0.3s;<br \/>\n  width:100%;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor273898 .ue-image-link<br \/>\n{<br \/>\n  display:block;<br \/>\n  color: unset;<br \/>\n}<\/p>\n<\/style>\n<div id=\"uc_ue_random_image_elementor273898\" class=\"ue-random-image\" data-debug=\"false\" data-editor=\"no\">\n<div class=\"ue-image\">\n<div class=\"ue-image-box\">\n<p>      <img decoding=\"async\" class=\"ue-image-item\" src=\"\"><\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!-- end Random Image - Middle --><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-3bdd3e0 elementor-widget elementor-widget-text-editor\" data-id=\"3bdd3e0\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The code on line 22 will make sure the game object on which the Singleton class is attached to will not get destroyed when we move between the scenes.<\/p>\n<p>We also created a function CreateSingleton so that we keep our code clean and organized which is the right way to code, contrary to what all other tutorials and courses show where they have code scattered all over the place, especially in the Awake function.<\/p>\n<p>So always make sure to group your code which will make it more clean and readable and essentially this how you need to code if you want to get hired in a game studio.<\/p>\n<p>Now our Singleton is persistent across scenes:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-81cfba3 elementor-aspect-ratio-169 elementor-widget elementor-widget-video\" data-id=\"81cfba3\" data-element_type=\"widget\" data-settings=\"{\" youtube_url\":\"https:=\"\" youtu.be=\"\" cdpzkhxepvw\",\"video_type\":\"youtube\",\"controls\":\"yes\",\"aspect_ratio\":\"169\"}\"=\"\" data-widget_type=\"video.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-wrapper elementor-fit-aspect-ratio elementor-open-inline\">\n<div class=\"elementor-video\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-cab8f0d elementor-widget elementor-widget-text-editor\" data-id=\"cab8f0d\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The code we added does not only make our Singleton class persistent across scenes, but it also prevents from having copies of the same Singleton by destroying the copy in the previous scene.<\/p>\n<p>Because our original Singleton is in Scene 1, when we go to Scene 2 there is not Singleton game object except the one that has transfered from Scene 1.<\/p>\n<p>But when we go back to Scene 1, the original Singleton object is there, but since we are calling the Destroy function on line 22 in the code above, the copy is destroyed and only one Singleton remains in the game.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-f1f6815 elementor-widget elementor-widget-heading\" data-id=\"f1f6815\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">Different Examples Of Setting Up A Singleton Pattern<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-5911605 elementor-widget elementor-widget-text-editor\" data-id=\"5911605\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Same as with anything in programming there are multiple ways how to do things and of course, there are multiple ways to set up a Singleton class.<\/p>\n<p>You\u2019ll probably encounter some examples online, so we\u2019ll list the common ones here because not all of them are easy to read and in our personal opinion look a little complicated but since you\u2019ll see them anyway, might as well know how they look like.<\/p>\n<p>We\u2019ll list the examples below and use comments in the code to explain what is going on.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-48eae4b elementor-widget elementor-widget-code-highlight\" data-id=\"48eae4b\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class Singleton : MonoBehaviour\n{\n    \/\/ declaring an instance of the singleton\n    \/\/ using the accessor method to create\n    \/\/ a public get and private set\n    \/\/ this will allow any class to get the instance variable\n    \/\/ but it will not allow anyone outside of this class\n    \/\/ to set the instance variable\n    public static Singleton instance { get; private set; }\n\n    private void Awake()\n    {\n        if (instance != null && instance != this)\n            Destroy(this);\n        else\n            instance = this;\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-6ffd889 elementor-widget elementor-widget-code-highlight\" data-id=\"6ffd889\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\npublic class Singleton : MonoBehaviour\n{\n    \/\/ declaring a private instance variable\n    private static Singleton instance = null;\n\n    \/\/ creating a public accessor that will get the instace\n    public static Singleton Instance\n    {\n        get\n        {\n            \/\/ test if the instance is null\n            \/\/ if so, try to get it using FindObjectOfType\n            if (instance == null)\n                instance = FindObjectOfType<Singleton>();\n\n            \/\/ if the instance is null again\n            \/\/ create a new game object\n            \/\/ attached the Singleton class on it\n            \/\/ set the instance to the new attached Singleton\n            \/\/ call don't destroy on load\n            if (instance == null)\n            {\n                GameObject gObj = new GameObject();\n                gObj.name = \"Singleton\";\n                instance = gObj.AddComponent<Singleton>();\n                DontDestroyOnLoad(gObj);\n            }\n            return instance;\n        }\n    }\n\n    private void Awake()\n    {\n        if (instance == null)\n        {\n            instance = this;\n            DontDestroyOnLoad(gameObject);\n        }\n        else\n        {\n            Destroy(gameObject);\n        }\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-5f022c8 elementor-widget elementor-widget-text-editor\" data-id=\"5f022c8\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The example above is very commonly used in tutorials and courses but sadly doesn\u2019t follow good coding practices and writing clean code.<\/p>\n<p>It\u2019s just too many lines of code that can be written with way less and without the unnecessary adding of components and creating game objects.<\/p>\n<p>Moving forward we have the generic singleton implementation:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-9c4c1e1 elementor-widget elementor-widget-code-highlight\" data-id=\"9c4c1e1\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>using UnityEngine;\n\n\/\/ <> denotes this is a generic class\npublic class GenericSingleton<T> : MonoBehaviour where T : Component\n{\n    \/\/ create a private reference to T instance\n    private static T instance;\n\n    public static T Instance\n    {\n        get\n        {\n            \/\/ if instance is null\n            if (instance == null)\n            {\n                \/\/ find the generic instance\n                instance = FindObjectOfType<T>();\n\n                \/\/ if it's null again create a new object\n                \/\/ and attach the generic instance\n                if (instance == null)\n                {\n                    GameObject obj = new GameObject();\n                    obj.name = typeof(T).Name;\n                    instance = obj.AddComponent<T>();\n                }\n            }\n            return instance;\n        }\n    }\n\n    public virtual void Awake()\n    {\n        \/\/ create the instance\n        if (instance == null)\n        {\n            instance = this as T;\n            DontDestroyOnLoad(this.gameObject);\n        }\n        else\n        {\n            Destroy(gameObject);\n        }\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-c627593 elementor-widget elementor-widget-template\" data-id=\"c627593\" data-element_type=\"widget\" data-widget_type=\"template.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-template\">\n<div data-elementor-type=\"section\" data-elementor-id=\"31169\" class=\"elementor elementor-31169\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7eaceb00 elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"7eaceb00\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7542c05a\" data-id=\"7542c05a\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-7a156fc9 elementor-widget elementor-widget-ucaddon_ue_random_image\" data-id=\"7a156fc9\" data-element_type=\"widget\" data-widget_type=\"ucaddon_ue_random_image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t<!-- start Random Image - Middle --><\/p>\n<style type=\"text\/css\">\/* widget: Random Image - Middle *\/<\/p>\n<p>#uc_ue_random_image_elementor288779<br \/>\n{<br \/>\n  display:flex;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor288779 .ue-image-item<br \/>\n{<br \/>\n  display:block;<br \/>\n  transition:0.3s;<br \/>\n  width:100%;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor288779 .ue-image-link<br \/>\n{<br \/>\n  display:block;<br \/>\n  color: unset;<br \/>\n}<\/p>\n<\/style>\n<div id=\"uc_ue_random_image_elementor288779\" class=\"ue-random-image\" data-debug=\"false\" data-editor=\"no\">\n<div class=\"ue-image\">\n<div class=\"ue-image-box\">\n<p>      <img decoding=\"async\" class=\"ue-image-item\" src=\"\"><\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!-- end Random Image - Middle --><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-0bee524 elementor-widget elementor-widget-text-editor\" data-id=\"0bee524\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>If for example, you want to use the generic singleton class for the UI manager you would create the class like this:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-80cbd38 elementor-widget elementor-widget-code-highlight\" data-id=\"80cbd38\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public class UIManager : GenericSingleton<UIManager>\n{\n\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-f790138 elementor-widget elementor-widget-text-editor\" data-id=\"f790138\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Let\u2019s assume that the UIManager class has a function to load the game from the main menu:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-5678f2e elementor-widget elementor-widget-code-highlight\" data-id=\"5678f2e\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public class UIManager : GenericSingleton<UIManager>\n{\n    public void LoadGame()\n    {\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-d586387 elementor-widget elementor-widget-text-editor\" data-id=\"d586387\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>This is how we would call the LoadGame function from another class:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-06905fa elementor-widget elementor-widget-code-highlight\" data-id=\"06905fa\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>UIManager.Instance.LoadGame();<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4faa6a6 elementor-widget elementor-widget-text-editor\" data-id=\"4faa6a6\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>This is a nice way to set up a generic Singleton class if you\u2019re going to have multiple classes in your project.<\/p>\n<p>Next, we\u2019ll cover simple examples that\u2019ll show you how to use the Singleton pattern in your project in the most efficient and simplest way possible without leaving a single chance to have any issues when the project gets bigger.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-7232d70 elementor-widget elementor-widget-heading\" data-id=\"7232d70\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">The Dangers Of The Singleton Pattern<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-df0fb32 elementor-widget elementor-widget-text-editor\" data-id=\"df0fb32\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>As we already mentioned, a lot of game programmers will say that you should not use the Singleton pattern. Even more software developers will say that.<\/p>\n<p>But again, it all comes back to how you\u2019re using the pattern.<\/p>\n<p>What most game devs do is saturate the singleton pattern. They put too much things inside and too many responsibilities for the Singleton.<\/p>\n<p>Here\u2019s one example when using the Singleton pattern as an audio manager:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-97ac6e4 elementor-widget elementor-widget-code-highlight\" data-id=\"97ac6e4\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public class AudioManager : MonoBehaviour\n{\n    public static AudioManager instance;\n\n    private AudioSource audioPlayer;\n\n    [SerializeField]\n    private AudioClip footstepSound, shootingSound, coinSound, gameOverSound;\n\n    private void Awake()\n    {\n        audioPlayer = GetComponent<AudioSource>();\n\n        if (instance != null)\n            Destroy(gameObject);\n        else\n            instance = this;\n\n        DontDestroyOnLoad(gameObject);\n    }\n\n    public void PlayFootstepSound()\n    {\n        audioPlayer.clip = footstepSound;\n        audioPlayer.Play();\n    }\n\n    public void PlayShootingSound()\n    {\n        audioPlayer.clip = shootingSound;\n        audioPlayer.Play();\n    }\n\n    public void PlayCoinSound()\n    {\n        audioPlayer.clip = coinSound;\n        audioPlayer.Play();\n    }\n\n    public void PlayGameOverSound()\n    {\n        audioPlayer.clip = gameOverSound;\n        audioPlayer.Play();\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-ebae307 elementor-widget elementor-widget-text-editor\" data-id=\"ebae307\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>As crazy as this setup looks, sadly it\u2019s very common to find in YouTube tutorials and paid courses.<\/p>\n<p>The issue with this setup is that the Singleton class should not be responsible for holding references for the sounds it needs to play.<\/p>\n<p>Also it should not have a separate function for every sound. There should be one function that can play the sound effect needed at that time.<\/p>\n<p>The bottom line is, to make the Singleton efficient you need to use it for just one purpose and don\u2019t give it more responsibility than it needs.<\/p>\n<p>Next we are going to take a look at a few examples how to use the Singleton class the right way which will allow you to create games easier and have better project structure.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-0e0fb02 elementor-widget elementor-widget-heading\" data-id=\"0e0fb02\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">How To Use The Singleton Pattern The Right Way<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-e438e5b elementor-widget elementor-widget-text-editor\" data-id=\"e438e5b\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Starting with the previous examples of having an audio manager Singleton, how can we re-write the code to make the Singleton more efficient and not introduce bugs later on.<\/p>\n<p>Here\u2019s the correct version of the audio manager Singleton:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-d1ffeb4 elementor-widget elementor-widget-code-highlight\" data-id=\"d1ffeb4\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public class AudioManager : MonoBehaviour\n{\n    public static AudioManager instance;\n\n    private AudioSource audioPlayer;\n\n    private void Awake()\n    {\n\n        audioPlayer = GetComponent<AudioSource>();\n\n        if (instance != null)\n            Destroy(gameObject);\n        else\n            instance = this;\n\n        DontDestroyOnLoad(gameObject);\n    }\n\n    public void PlaySound(AudioClip soundToPlay)\n    {\n        \/\/ example 1\n        audioPlayer.clip = soundToPlay;\n        audioPlayer.Play();\n\n        \/\/ example 2\n        audioPlayer.PlayOneShot(soundToPlay);\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-e181988 elementor-widget elementor-widget-text-editor\" data-id=\"e181988\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Here we follow the single responsibility principle where we created the audio manager and gave it only one responsibility which is to play the audio clip that we pass to its PlaySound function. That\u2019s it.<\/p>\n<p>The audio clips are going to be in other classes such as Player, Enemy, Coin, and so on.<\/p>\n<p>Because it\u2019s not the responsibility of the audio manager to have references of the audio clips it needs to play.<\/p>\n<p>Now let\u2019s say we have a few variables that need to be shared across the project like score, kill count, and so on.<\/p>\n<p>This is how we would structure the Singleton class that will hold those variables:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-68d9896 elementor-widget elementor-widget-code-highlight\" data-id=\"68d9896\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public class GameplayManager : MonoBehaviour\n{\n    public static GameplayManager instance;\n\n    private int score;\n    private int killCount;\n\n    private void Awake()\n    {\n        if (instance == null)\n            instance = this;\n        else\n            Destroy(gameObject);\n\n        DontDestroyOnLoad(gameObject);\n    }\n\n    public int GetScore()\n    {\n        return score;\n    }\n\n    public int GetKillCount()\n    {\n        return killCount;\n    }\n\n    public void IncreaseScore(int amount)\n    {\n        score += amount;\n    }\n\n    public void IncreaseKillCount(int amount)\n    {\n        killCount += amount;\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-3df7df3 elementor-widget elementor-widget-text-editor\" data-id=\"3df7df3\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Again, we see that the GameplayManager class has only one responsibility: holding the variables and having functions to change them and get their value.<\/p>\n<p>So when the player kills an enemy in the game we simply call:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-7416cc1 elementor-widget elementor-widget-code-highlight\" data-id=\"7416cc1\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>GameplayManager.instance.IncreaseKillCount(1);<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-3f2b954 elementor-widget elementor-widget-text-editor\" data-id=\"3f2b954\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>And in the UI manager that will display the kill count score, would simply pass the variable:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-1ca406a elementor-widget elementor-widget-code-highlight\" data-id=\"1ca406a\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>UIManager.Instance.DisplayKillCount(GameplayManager.instance.GetKillCount());<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-f608cfb elementor-widget elementor-widget-text-editor\" data-id=\"f608cfb\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Another thing we\u2019ve seen tutorials, courses, and game devs in general do wrong is mix accessors with getters and setters like this:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-a39e9e7 elementor-widget elementor-widget-code-highlight\" data-id=\"a39e9e7\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>UIManager.Instance.DisplayKillCount(GameplayManager.instance.GetKillCount());apublic class GameplayManager : MonoBehaviour\n{\n    public static GameplayManager instance;\n\n    private int score;\n    private int killCount;\n\n    private void Awake()\n    {\n        if (instance == null)\n            instance = this;\n        else\n            Destroy(gameObject);\n\n        DontDestroyOnLoad(gameObject);\n    }\n\n    \/\/ using accessor\n    public int Score\n    {\n        get { return score; }\n    }\n\n    \/\/ using accessor\n    public int KillCount\n    {\n        get { return killCount; }\n    }\n\n    \/\/ using setter\n    public void IncreaseScore(int amount)\n    {\n        score += amount;\n    }\n\n    \/\/ using setter\n    public void IncreaseKillCount(int amount)\n    {\n        killCount += amount;\n    }\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-6017107 elementor-widget elementor-widget-template\" data-id=\"6017107\" data-element_type=\"widget\" data-widget_type=\"template.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-template\">\n<div data-elementor-type=\"section\" data-elementor-id=\"31169\" class=\"elementor elementor-31169\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7eaceb00 elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"7eaceb00\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7542c05a\" data-id=\"7542c05a\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-7a156fc9 elementor-widget elementor-widget-ucaddon_ue_random_image\" data-id=\"7a156fc9\" data-element_type=\"widget\" data-widget_type=\"ucaddon_ue_random_image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t<!-- start Random Image - Middle --><\/p>\n<style type=\"text\/css\">\/* widget: Random Image - Middle *\/<\/p>\n<p>#uc_ue_random_image_elementor295488<br \/>\n{<br \/>\n  display:flex;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor295488 .ue-image-item<br \/>\n{<br \/>\n  display:block;<br \/>\n  transition:0.3s;<br \/>\n  width:100%;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor295488 .ue-image-link<br \/>\n{<br \/>\n  display:block;<br \/>\n  color: unset;<br \/>\n}<\/p>\n<\/style>\n<div id=\"uc_ue_random_image_elementor295488\" class=\"ue-random-image\" data-debug=\"false\" data-editor=\"no\">\n<div class=\"ue-image\">\n<div class=\"ue-image-box\">\n<p>      <img decoding=\"async\" class=\"ue-image-item\" src=\"\"><\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!-- end Random Image - Middle --><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-fb8dfa8 elementor-widget elementor-widget-text-editor\" data-id=\"fb8dfa8\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>This is the wrong way to mix and match different setups in the code which can be confusing to read, especially for other programmers working on the same project.<\/p>\n<p>So be careful how you set up the class structure.<\/p>\n<p>The two examples above will be enough for you to create a Singleton for any purpose in your game.<\/p>\n<p>Just remember, the Singleton should only be responsible for its tasks and be separated from other classes.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4943eb7 elementor-widget elementor-widget-heading\" data-id=\"4943eb7\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">How To Use The Singleton Pattern To Reduce Bugs In Your Unity Project<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4c14e03 elementor-widget elementor-widget-text-editor\" data-id=\"4c14e03\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Writing code is a form of art. One thing that we\u2019ve noticed with game programmers, and programmers in general is that they just follow the \u201crules\u201d someone laid out and don\u2019t even try to think outside of those rules.<\/p>\n<p>For example, using the Singleton pattern principle we\u2019ve developed a simple way to have all your hard coded variables in one place which will ensure that you never introduce a bug in your code when using variables for built in functions.<\/p>\n<p>Funny thing is that other game devs have contacted us and left comments on our YouTube channel how they introduced the TagManager principle in the game studio they work, and now the whole game studio is using that principle when coding their games.<\/p>\n<p>Here\u2019s an example of a class we call TagManager which holds all the strings we\u2019re going to use in the project to compare objects to each other:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-8a404a1 elementor-widget elementor-widget-code-highlight\" data-id=\"8a404a1\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>public static class TagManager\n{\n    public const string ENEMY_TAG = \"Enemy\";\n    public const string PLAYER_TAG = \"Player\";\n\n    public const string COIN_TAG = \"Coin\";\n}<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4c174fe elementor-widget elementor-widget-text-editor\" data-id=\"4c174fe\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>When you want to compare objects to each other you simply use the TagManager class to pass the string parameters:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4c30c88 elementor-widget elementor-widget-code-highlight\" data-id=\"4c30c88\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>private void OnTriggerEnter2D(Collider2D other)\n    {\n        if (other.CompareTag(TagManager.PLAYER_TAG))\n        {\n            \/\/ collided with player\n        }\n\n        if (other.CompareTag(TagManager.ENEMY_TAG))\n        {\n            \/\/ collided with enemy\n        }\n\n        if (other.CompareTag(TagManager.COIN_TAG))\n        {\n            \/\/ collided with coin\n        }\n    }<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-df7802a elementor-widget elementor-widget-text-editor\" data-id=\"df7802a\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>What tutorials and other courses show you is this:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-4839d59 elementor-widget elementor-widget-code-highlight\" data-id=\"4839d59\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp>private void OnTriggerEnter2D(Collider2D other)\n    {\n        if (other.CompareTag(\"Player\"))\n        {\n            \/\/ collided with player\n        }\n\n        if (other.CompareTag(\"Enemy\"))\n        {\n            \/\/ collided with enemy\n        }\n\n        if (other.CompareTag(\"Coin\"))\n        {\n            \/\/ collided with coin\n        }\n    }<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-e95366e elementor-widget elementor-widget-text-editor\" data-id=\"e95366e\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>If you compare the TagManager approach to the example above you\u2019ll see how much more efficient the TagManager approach is because you can call it in multiple places and if by any chance you have an error, you only need to fix it inside the TagManager class.<\/p>\n<p>Using the approach above you would have to go in every class where you have the appropriate tag to adapt the string to the tag change.<\/p>\n<p>Even if you use something like this:<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-9aea6bc elementor-widget elementor-widget-code-highlight\" data-id=\"9aea6bc\" data-element_type=\"widget\" data-widget_type=\"code-highlight.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"prismjs-tomorrow copy-to-clipboard \">\n<pre data-line=\"\" class=\"highlight-height language-csharp line-numbers\">\t\t\t\t<code readonly=\"true\" class=\"language-csharp\">\n\t\t\t\t\t<xmp> private string playerTag = \"Player\";\n    private string enemyTag = \"Player\";\n    private string coinTag = \"Player\";\n\n    private void OnTriggerEnter2D(Collider2D other)\n    {\n        if (other.CompareTag(playerTag))\n        {\n            \/\/ collided with player\n        }\n\n        if (other.CompareTag(enemyTag))\n        {\n            \/\/ collided with enemy\n        }\n\n        if (other.CompareTag(coinTag))\n        {\n            \/\/ collided with coin\n        }\n    }<\/xmp>\n\t\t\t\t<\/code>\n<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-ed3e63d elementor-widget elementor-widget-text-editor\" data-id=\"ed3e63d\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>Even though the example above is a lot better than using raw hardcoded strings, it\u2019s still not efficient because if you\u2019re using the tag in multiple classes, any changes to the tag you\u2019ll have to also apply in all classes where you use that particular tag.<\/p>\n<p>So be careful about the tutorials you\u2019re following and always make sure to double check if what they\u2019re teaching you is a good way or a bad way to code.<\/p>\n<p>And most importantly don\u2019t be afraid to come up with your own solutions like we did with the TagManager.<\/p>\n<p>Always experiment and try new things and that\u2019s how you grow as a game programmer and that\u2019s how you\u2019ll gain the skills to get hired in a game studio.<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-df0d19f elementor-widget elementor-widget-heading\" data-id=\"df0d19f\" data-element_type=\"widget\" data-widget_type=\"heading.default\">\n<div class=\"elementor-widget-container\">\n<h3 class=\"elementor-heading-title elementor-size-default\">Where To Go From Here<\/h3>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-2232091 elementor-widget elementor-widget-text-editor\" data-id=\"2232091\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n<div class=\"elementor-widget-container\">\n<p>The fundamentals of game development and game programming patterns are the most important skills you need to have to get hired in a game studio.<\/p>\n<p>The Singleton pattern is just one of the many game programming patterns available that game studios are using to create their games.<\/p>\n<p>We cover game programming patterns in-depth inside Game Dev Pro which you can check out by clicking the link below:<\/p>\n<p>Game Dev Pro<\/p>\n<p>You can also check out our other posts for coroutines, delegates, and events which are also important and advanced concepts to know if you plan to get hired in a game studio:<\/p>\n<p>Delegates And Events In Unity<\/p>\n<p>Coroutines In Unity<\/p>\n<\/div>\n<\/div>\n<div class=\"elementor-element elementor-element-0c78020 elementor-widget elementor-widget-template\" data-id=\"0c78020\" data-element_type=\"widget\" data-widget_type=\"template.default\">\n<div class=\"elementor-widget-container\">\n<div class=\"elementor-template\">\n<div data-elementor-type=\"section\" data-elementor-id=\"31169\" class=\"elementor elementor-31169\">\n<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7eaceb00 elementor-section-full_width elementor-section-height-default elementor-section-height-default\" data-id=\"7eaceb00\" data-element_type=\"section\" data-settings=\"{\" jet_parallax_layout_list\":[]}\"=\"\">\n<div class=\"elementor-container elementor-column-gap-default\">\n<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7542c05a\" data-id=\"7542c05a\" data-element_type=\"column\">\n<div class=\"elementor-widget-wrap elementor-element-populated\">\n<div class=\"elementor-element elementor-element-7a156fc9 elementor-widget elementor-widget-ucaddon_ue_random_image\" data-id=\"7a156fc9\" data-element_type=\"widget\" data-widget_type=\"ucaddon_ue_random_image.default\">\n<div class=\"elementor-widget-container\">\n\t\t\t<!-- start Random Image - Middle --><\/p>\n<style type=\"text\/css\">\/* widget: Random Image - Middle *\/<\/p>\n<p>#uc_ue_random_image_elementor300039<br \/>\n{<br \/>\n  display:flex;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor300039 .ue-image-item<br \/>\n{<br \/>\n  display:block;<br \/>\n  transition:0.3s;<br \/>\n  width:100%;<br \/>\n}<\/p>\n<p>#uc_ue_random_image_elementor300039 .ue-image-link<br \/>\n{<br \/>\n  display:block;<br \/>\n  color: unset;<br \/>\n}<\/p>\n<\/style>\n<div id=\"uc_ue_random_image_elementor300039\" class=\"ue-random-image\" data-debug=\"false\" data-editor=\"no\">\n<div class=\"ue-image\">\n<div class=\"ue-image-box\">\n<p>      <img decoding=\"async\" class=\"ue-image-item\" src=\"\"><\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!-- end Random Image - Middle --><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/section>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Singleton is a design pattern that is used as a container which holds values that can be globally accessible across the whole project. Singletons are very useful because they can transfer game data from scene to scene without the need to save and load data in the background. There\u2019s also a debate amongst game programmers<\/p>\n","protected":false},"author":1,"featured_media":979,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-849","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/posts\/849"}],"collection":[{"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=849"}],"version-history":[{"count":2,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/posts\/849\/revisions"}],"predecessor-version":[{"id":980,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/posts\/849\/revisions\/980"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=\/wp\/v2\/media\/979"}],"wp:attachment":[{"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=849"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=849"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/globalgoodplay.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=849"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}