• Register

Mire Studios is made up of two people who have always enjoyed playing games. We're gamers that make games so you can expect a wide variety of different games from us.

RSS My Blogs

Unity Self Creating Singleton Template

Mire_Studios Blog

Sometimes, you need globally accessible data. Although I'm not going to go into the whole thing debate about global data. I have noticed, that in Unity, a Singleton is sometimes a good way to move temporary data across scenes.

If you go search the web, you will see many examples of how to create Singletons in Unity. However, most of them require you to copy some boilerplate code into every script and having to copy code from one script into another is never a good idea. They also don't create themselves or do it in a weird way.

Here's our solution, a Singleton template. This abstract class puts all of the boilerplate into one script and has the bonus of the Singleton creating itself when it's requested by another script. This means, that if you forget to place a GameObject with the script into a scene, it will be created for you.

Below you will find two, slightly different examples of the Singleton template. I will explain them after showing the code:

    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _instance;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    var create = new GameObject(string.Concat(typeof(T),  
                    " Singleton")).AddComponent<T>();
                    _instance = create;
                }

                return _instance;
            }
        }

        protected virtual void Awake()
        {
           if (_instance == null)
              _instance = this as T;
           else
              Destroy(gameObject);

            DontDestroyOnLoad(gameObject);
        }
    }

This implementation will simply create the object if it's null as you see in the getter. This is good if you have an object where the values are not exposed to the editor. If you are using a Singleton that has values that must be set in the editor. The following will suit you better:

    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _instance;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    var create = Instantiate(Resources.Load(Prefab)) as T;
                    _instance = create;
                }

                return _instance;
            }
        }
        
        protected abstract string Prefab { get; }        

        protected virtual void Awake()
        {
             if (_instance == null)
                _instance = this as T;
             else
                Destroy(gameObject);

            DontDestroyOnLoad(gameObject);
        }
    }

This implementation requires that you have the object saved as a prefab in the Resources Folder. This will create the object, in case you forgot it, and will keep the values as it's a prefab. The main difference here is that the singleton will need to implement the "Prefab" field. Where you must simply just return the string name of the prefab you want to instantiate, easy.

Now to go over what these scripts do in more detail. If the singleton is already in the scene, a new one won't be created. Second, if there are multiple singletons the others will be destroyed so that there will only be one. Finally, to use the script, simply inherit from it and do what you would normally do with any other Singleton. The "T" parameter is simply the class that you pass in. Here's a quick example:

public class TestSingelton : MonoSingleton<TestSingleton>
{
   private void Start()
   {
      Debug.Log("I am a Singleton");
   }
}

Notice that you pass in the same class type as is inheriting the script. Pretty simple, right? If you any questions about these two Singleton templates, let us know in the comments below.

Until next time.

Unity Get Reference To An Interface

Mire_Studios Blog

This is just a quick thing we've noticed that not a lot of people seem to know about. In Unity, you can actually use GetComponent to find an interface. Here's how you can go about doing that.

public class MyBehaviour : MonoBehaviour
{
   private IMyInterface myInterface;
   
   private void Awake()
   {
      myInterface = GetComponent(typeof(IMyInterface))
      as IMyInterface;
   }
}

Notice that this works a little bit differently than when normally using GetComponent. Also make note that you must cast the component to the interface type that you are looking for or you'll get an error.

That's it, just a quick tip for you guys that want to use interfaces in your project in that manner.

Until next time.

Unity Getting Rid Of (Some) Drag And Drop References Part 5

Mire_Studios Blog

I'm going to assume you've read up to part 4 of the this tutorial/tips series. If not, make sure to do so before reading on.

So let's make a quick, simple, and slightly contrived example on how to put together the things we've learned. Let's assume we have a Player script and an Inventory script. We want the Player script to open up the Inventory when pressing the "I" key on the keyboard. That will call the Inventory.Open() method and, well, open the Inventory.

Create two empty GameObjects in your scene. Name one Player and name the other Inventory. Then, create two scripts with the same names as above. Attach each script to the GameObject object of the same and name and that's it.

public class Player : MonoBehaviour
{
   private Inventory inventory;

   private void Awake()
   {
      // way to get reference 1
      inventory = FindObjectOfType<Inventory>();

      // way to get reference 2
      inventory = GameObject.FindWithTag("Inventory").
      GetComponent<Inventory>();
   }

   private void Update()
   {
      if(Input.GetKeyDown(KeyCode.I))
      {
         inventory.Open();
      }
   }
}

I included two different ways of getting a reference to the inventory script in the Awake method. Obviously you would only need one or the other. I won't go over them because they have been covered in the previous tutorials/tips. As you can see, we can get a reference to our inventory without having to drag anything in the inspector.

Let's take a look at the Inventory script

public class Inventory : MonoBehaviour
{
   public void Open()
   {
      Debug.Log("Opened the inventory without a drag and
      drop reference, awesome"); 
   }
}

Obviously not what we'd want an Inventory to actually do but it gives you the idea. Instead of declaring a public Inventory reference on the Player script and then having to drag and drop the script in the inspector. We instead have Unity methods do the work for us.

That's it for this tutorial/tips series. I may create some more in the future but only if you guys liked this series. Let me know in the comments, or, feel free to send an email to mirestudios@gmail.com either way works. I'll see you guys around.

Unity Getting Rid Of (Some) Drag And Drop References Part 4

Mire_Studios Blog

This is part 4 our new Unity programmer tutorial/tips. I assume you've read up to part 3. If not, make sure you do so before reading on.

Yesterday, we covered tags and how they can help get rid of drag and drop references. What if we want a reference to a script that there is only one of and don't want to use a tag? We can use FindObjectOfType. Let's see it in action.

public class Thing : MonoBehaviour
{
   private OtherThing otherThing;

   private void Awake()
   {
      otherThing = FindObjectOfType<OtherThing>();
   }

   private void Update()
   {
      otherThing.Do();
   }
}

I think this one should be pretty simple to understand. FindObjectOfType will find an Object of the desired type. In this case we want a reference for otherThing.

This seems like it's way easier to use than setting up a tag system right? Well, it is but it has a slight drawback. FindObjectOfType runs slowly. That doesn't mean, however, that you can't use it. That's why it exists in the first place. It's a nice, easy, Unity way of getting a reference to an object without having to drag and drop it in. Also, keep in mind the word "slow" in programing is relative. If it's working and isn't slowing down your application then it's fine and as a beginner it will start making you think of other ways you can do the same thing more efficiently.

Lastly, what if we want an array or list of something? FindObjectsOfType, with an "s", can work just fine.

That's the end of this blog post. Tomorrow, we'll put this all together in a very simple way to help you understand how to use these functions. See you then.

Unity Getting Rid Of (Some) Drag And Drop References Part 3

Mire_Studios Blog

Today we'll picking up from part 2. I'm going assume you've read the previous parts. If not, make sure to do so before reading on.

So what if you need a reference to something but it's not on the GameObject? Yesterday we talked about how you can get references on the same GameObject, GetComponent. Well, we could use tags to get references from another GameObject.

To set up a tag, simply find a GameObject in the scene and in the inspector window find the tag dropdown. Unity has a few default tags but you can also add your own. Make sure the tag/s you want are added or you will get in error when trying to find the tag in code.

Let's see an example of how to use it.

public class Thing : MonoBehaviour
{
   public string tagToSearchFor;
   private OtherThing otherThing;

   private void Awake()
   {
      otherThing =
      GameObject.FindGameObjectWithTag(tagToSearchFor).
      GetComponent<OtherThing>();
   }

   private void Update()
   {
      otherThing.Do();
   }
}

So what are we doing here? We've defined a public string tagToSearchFor. That should be pretty self explanatory. That string value can be set in the inspector just in case we want use this script multiple times for GameObjects with different tags. Next, we call GameObject.FindGameObjectWithTag(tagToSearchFor). This function simply looks for a GameObject of the tag we want. Finally, we have to call GetComponent from the GameObject that has just been found and that will get us our reference for otherThing.

What if we want an array or list of GameObjects with a certain tag? Well, we can use GameObject.FindGameObjectsWithTag. It works the same way but will return an array of GameObject instead of one with the tag you're searching for.

That's it for this blog post. Tomorrow we will look at one more way to get rid of drag and drop references. I'll see you then.

Unity Getting Rid Of (Some) Drag And Drop References Part 2

Mire_Studios Blog

let's pick up from where we left off yesterday. I'm going to assume that you've already read part 1.

So today I'm going to start covering Unity ways to get rid of drag and drop references. These will be very easy for new programmers to understand and will help you get rid of some of those pesky references.

First off we have GetComponent. I'm going to show you how to use this by modifying the code from yesterday. After that, I'll explain what it does.

public class Thing : MonoBehaviour
{
   private OtherThing otherThing;

   private void Awake()
   {
      otherThing = GetComponent<OtherThing>();
   }

   private void Update()
   {
      otherThing.Do();
   }
}

First of all, we made our OtherThing reference private because we no longer need it to be shown in the inspector. In the Awake function (note: Awake is the first Unity function that gets called once on startup) we get a reference to OtherThing by using GetComponent. So what does it do? GetComponent will find the first script of the specified type. In the example OtherThing is our type. If we have an OtherThing script dragged onto the GameObject then it will be found and used a reference. No dragging and dropping required.

Ok, so when do we use this? You can use GetComponent anytime that one of your scripts requires something that is on the same GameObject. Make note of that last part, the same GameObject. GetComponent will not find the reference if it's on another GameObject.

So what if we have multiple? The answer to that is to use GetComponents, with an "s" at the end. That will find all objects of that type on your GameObject. Useful if you have an array or a list that you need to populate.

That's it for this blog post. Tomorrow we'll continue by looking at another way to reduce drag and drop references, tags.

Unity Getting Rid Of (Some) Drag And Drop References

Mire_Studios Blog

This blog post is intended for Unity users who are still new to scripting but have a few basics worked out.
I'm going to assume you know the following:

  • Basic C# knowledge
  • Basic knowledge of scripting in Unity
  • Understand how to navigate around the Unity editor

Are you often writing code like this?

public class Thing : Monobehaviour
{
   public OtherThing otherThing;

   private void Update()
   {
      otherThing.Do();
   }
}

Then you go to the Unity inspector and add the drag and drop the GameObject that contains OtherThing onto Thing? This is an incredibly easy way to get references to objects but causes quite a few issues.

Having to drag and drop all of your references quickly gets out of control and becomes quite tedious. Imagine having to drag and drop multiple references on even 10 or so GameObjects within your scene. This is also not including the fact that it may be confusing for someone else to wire up your scripts.

So how can we go about eliminating some of these drag and drop references. Well, you might do a quick Google search and see people talking about different design patterns to help with this problem. However, I assume that you do not know anything about design patterns much less know which ones to use. Is there a simple to understand Unity way of doing this? The answer is yes and there are actually a few ways to go about it.

I want to keep these blog posts relatively short so that it's easier to absorb the information. Tomorrow, we will go about different Unity ways of solving our issues. I'll see you then.

Unity Tutorials

Mire_Studios Blog

Hey guys,

We've been thinking about writing some tutorials for Unity engine. Something for beginners that want to learn how to start programming in Unity. Start with the basics and then build up from there.

We know that there are many tutorial out on the Internet but a lot of them seem to focus more on "wow" rather than how or why. The other problem we've noticed is that there doesn't seem to be some of kind of middle ground for beginners to build up from. Most tutorials seem to either focus on beginners or advanced users.

If anyone thinks that's a good idea let us know and we'll get to work on posting a few.

Releasing A Game

Mire_Studios Blog

Having released our first game, Shrines of Eternity, two days ago really taught us a lot about the game development process.

Even with such a small game, there are many things that have to be considered. I'm going to break down some things that I feel are important when creating a game. These things are probably going to sound very obvious for more experienced developers but I think these tips will be very beneficial to newer developers, like us.

  1. Write a design document, really. You may think you can store the entire game in your head but that's not going to happen. Also, writing down how you want the game to work may reveal some problems with the design of the game.
  2. Organize your project well. Regardless of the game engine you use, you have to make sure that your project is easy to navigate. If it starts becoming difficult to find things in your project then you will want to consider organizing it better. Less time having to find things means more time actually working on your game.
  3. This one is for new programmers. Code the game the way you know how to do it. Even if what you're doing isn't the most efficient or best way, do it anyway. Then, when you look back at your work, you will be able to figure out the areas you need to improve on.
  4. Release the game. You can polish your game forever because you can always find small things that can be improved. Be it code improvements, polish, or anything else. Once your game is in a good, relatively, bug free state, release it.
  5. If you can't implement a feature either remove it, replace, or rework it. The reason as to why you may not be able to implement the feature can be many. Be it not having the technical skill, limitations due to the game engine, etc.
  6. Start small make a game that you can actually finish because it's more enjoyable to work on something that you can finish even if you have no intention of releasing it. You will also see yourself improve as you create new games.
  7. Making a game isn't easy so don't go about it as if it is. Games are tough to make but it's also very rewarding to see your finished, playable, product.

I could probably go on and on with more tips but I feel that these are some good aspects to take into consideration when developing a game.

If there's anything else you feel is important for a new developer to know then let us know in the comments section.

If you're curious to try out our game. You can check it out here link . It's free to download and play so go ahead and give it a go.