Obligatory Singleton Post

using UnityEngine;
using System.Collections;

public class Singleton : Monobehaviour
{
   public static Singleton instance;

   void Awake()
   {
      if(instance == null)
      {
         instance = this;
         DontDestroyOnLoad(gameObject);
      }
      else if(instance != this)
      {
         Destroy(gameObject);
      }
   }
}

This is the Singleton I often use when developing in Unity. I’ve spent the past few days doing some more in depth research for using Singletons specifically for game development in Unity. I’ve learned a few things; first, everyone and their dog has written a post on Singletons, secondly, there are an endless amount of developers arguing the merits and woes of Singletons, and lastly I’ve learned that even though there are many implementations of Singletons, this basic pattern handles most scenarios.  These things have given me inspiration as to the direction of future posts and this blog in general.  I am going to keep things concise and practical.  So without further ado, here is an example of a Singleton in use.

using UnityEngine;
using System.Collections;

public class Player : Monobehaviour
{
   public static Player instance;
   public int health = 100;

   void Awake()
   {
      if(instance == null)
      {
         instance = this;
         DontDestroyOnLoad(gameObject);
      }
      else if(instance != this)
      {
         Destroy(gameObject);
      }
   }
}

In this Player class we have added health and made it Public. This is important if you want to give other scripts access to this variable.

using UnityEngine;
using System.Collections;

public class Sword : Monobehaviour
{
   void Update()
   {
      if(Input.GetKeyDown(KeyCode.Return))
      {
         Slash();
         print(Player.instance.health.ToString());
      }
   }

   void Slash()
   {
      Player.instance.health -= 30;
   }
}

In this Sword class we have a Slash function that accesses the Player’s health and subtracts it by 30. In the Update function I’ve added some code to test Slash. It does indeed go down by 30. I realize the Player can now have negative health but for the sake of simplicity I’ll leave it there as it already demonstrates a Singleton.

Considerations

  1. DontDestroyOnLoad() only works with root GameObjects or components on root GameObjects.  Therefore you should leave DontDestroyOnLoad() off of child objects at least to save yourself from warnings filling up the console.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s