Design Pattern: Genuine Confusion

Hi Guys,

I’ve been studying up for a fair while on design patterns to use with Unity the past week. I’m still fairly confused with all the options, with no official go to from any Unity Tutorial. My research thus far has led me to these sites:

IoC & Dependency Injection
Blog Argument for IoC Containers for Unity: Lightweight IoC Container for Unity - part 1 - Seba's Lab
Indie Made IoC Container: Simple IoC Container for Unity3d - CodeProject
Asset Store - StrangeIoC: Unity Asset Store - The Best Assets for Game Making
Asset Store - Adic - Dependency Injection Container: Unity Asset Store - The Best Assets for Game Making
Asset Store Zenject Dependency Injection: Unity Asset Store - The Best Assets for Game Making

Singleton
Singleton Pattern with Delegate Array State Machine:

Argument For & Against Singleton Use: Using static function in Singleton, bad design? - Unity Engine - Unity Discussions
Singleton Pattern: http://wiki.unity3d.com/index.php/Singleton
Toolbox (Upgrade of Singleton): http://wiki.unity3d.com/index.php/Toolbox

State Machine
State Machine Tutorial:

Now I’m beginning a project that might span over a year or two, and am deeply considering different approaches for what design pattern to use. After all this, alongside KISS and YAGNI, I’m at a slight loss for what pattern to use still.

Overall from what I’m reading, they’re saying that IoC containers are generally much better, but less approachable than the Singleton Pattern. That you can’t Unit Test the Singleton Pattern, and that you can eventually get a jumbled mess of dependency. However using the IoC container is a fair amount of work (?? I’ve never used them), and you need to remember KISS and YAGNI, so an IoC Container may be unneccessary (?? Again I don’t know).

The problem is I’ve never used an IoC Container and I’m a bit green with them. I don’t know how easy they are, and whether they’re worth investing in something I’m not used to. I’ve made a lot of games using the Singleton pattern, but they tend to be 3-8 month projects. I’m not sure whether to start simple and expand, or plan the entire thing with a large(ish) framework.

Can anyone throw me any solid input?

Thanks!

I can only comment as an enterprise application developer as I’ve never created a game, much less a game using an IoC.

IoC are quite good at doing one thing: moving the responsibility of creating objects out of your domain object code. The fact that they are considered an alternative to singletons is a bit confounding. The alternative to singletons is not IoC, it is creating instances for each use. Personally, I like creating instances for each use because I find it easier to handle internal state and doing so allows objects to be easily swapped out for a different kinds of objects. That doesn’t mean I never use singleton – each design pattern has a use. The trouble is using them in ways that they weren’t really intended simply because it is convenient. Personally, I believe singleton use in games is one such example.

Of course, one has to be pragmatic. If you’ve never used an IoC before and you want to proceed, singletons offer a great way to start. If you’ve used singletons your whole life and never had a problem, you are probably really good at managing the pitfalls of such a design. In both cases, I say use the approach that gets you to where you want to be easiest. If you’re like me, and at least 50% of the motivation for any project is to learn something new, then trying out a pattern that may be a better match for the problem is the end unto itself: learning.

I’d also like point out it is easy to confuse what KISS and YAGNI are trying to tell us. Personally, I interpret KISS as a reminder to not get too clever with my algorithms, and YAGNI as a reminder to avoid feature creep. Neither are really related to design except YAGNI in regards to over-engineering. Like you said, you may not need an IoC for a 1-2 year project. Since I don’t have the experience, I can’t really comment on that except that I don’t think of IoC as over engineering on it’s own; it is simply a design decision. There are many implementations of IoC, some more complex than others.

Good luck on your project! I look forward to seeing more questions as you progress.

P.S. Possibly more valuable than all this design, is to make use of those who have gone before you. I haven’t been here long but I’ve seen a few very considerable framework contributions from the community that I can point out:
@dkoontz introduced me to the idea of Entity Component Systems here: RobotArms, a functional style Entity Component System for Unity - Unity Engine - Unity Discussions
@lordofduct has made large components of his game framework open source here on github. He’s also been quite active on this forum since I got here.

3 Likes

Don’t approach a project with the idea of what design patterns you’ll be using in the project.

Approach the project with what you need to solve to get the project done. And if those needs require things like inversion of control, then use it when it’s needed.

I personally have used inversion of control patterns in parts of my program, but that’s also because I was writing things that needed to be used in larger scopes than just my project as they may be used by me in several projects, or shared in my open source framework.

I could offer some ideas about how to use IoC within a component based design like those used in unity.

Currently I’m writing a tomagatchi style game I started last week where you have a vivarium in which you raise little people. There are items within the scene that the people should be able to interact with. To identify them we have a script called ‘InteractableAspect’.

Each item can have multiple InteractableAspect scripts attached them as child gameobjects, in case they have different ways to interact with them (imagine an apple that can be consumed for health, but also can be planted to grow a tree).

When the AI is considering what item to interact with next it searches nearby for any aspects. It then sorts them by a ‘precedence’ value which is just a float denoting how important that item is. Thing is, that precedence can change depending on the mood of the of AI, the state of the system (current health, if the AI has enough energy to use it, if the item can even be used currently for its purpose). So what I did was create an interface called ‘IInteractablePrecedenceModifier’:

public interface IInteractablePrecedenceModifier
{
     float AdjustPrecedence(float currentPrecedence, InteractableAspect aspect);
}

Now, the InteractableAspect collects these scripts off itself (similar to how most IoC objects can have their inverted control mechanism passed into them). When you try to retrieve its current precedence value, it loops over the modifiers it has, and it adjusts its precedence value per the modifiers it has. It then returns that modified precedence.

Lets say for instance I have a tree that can be shaken to get fruit from it. Usually its precedence is X. BUT if it has been interacted with, I want it to NOT be interacted with. So I have a ‘RecentlyInteractedWithPrecedanceModifier’ that returns NegativeInfinity from the ‘AdjustPrecedence’ method if it has been recently interacted with. This will cause it to fall to the bottom of the list of things to interact with, so that other items are chosen before it.

It’s IoC because the modifiers are controlled by whatever components are attached to the GameObject with the InteractableAspect that implement IInteractablePrecedenceModifier. There’s no hard dependency anymore.

Now, like I said though, I’m using this because that’s what I need. I didn’t go into the project saying “I’ll use the IoC pattern in this game”. I went into it thinking “I want to make a tamagatchi game”, and then I had to resolve the problem of selecting items based on importance based on the current state of the game. And the IoC pattern was the best option to solve my problem.

2 Likes

This should be in red, bold letters on top of the scripting forums.

Patterns are ways to solve problems. Only go in with “I’m going to use this pattern for everything” if you’re trying to undertand and/or learn about it.

2 Likes

Can I admit that my first thought on reading this thread was “What is he talking about?”

My general approach is as others have indicated. Fit the design pattern to the problem. Not the other way around.

About the only patterns you have to use are components and the game loop.

2 Likes

Thanks for all the feedback. I’m well used to putting something together and making it work. On the bottomline that’s really what is needed. That it works.

Generally with other projects, for better or worse, normally I’d make a Singleton instance, such as GameController, ActorFactor, InputManager, ect, inside an empty gameobject, which would hold the core states of the game, and handle a bit like a finite state machine. Other mini systems within the game I’d handle differently, as fits best. A bit like what you guys are suggesting for the most part :).

With a bigger project I’m looking ahead to refactoring, maintainability, extensibility, and possibly unit testing. How do you handle dependencies as you continue? I mean a lot of the time you can avoid direct dependencies and have interscript communication through things like collision, raytracing, abstraction, interfaces, GetComponent, accessing children. However with all that I’m still finding some classes need direct dependencies? Is this a sign of bad coding practices? Is it a natural event with Unity? I’ve been reading through this: http://www.sebaslab.com/ioc-container-for-unity3d-part-1/, which seems to describe my problem perfectly. What other people’s opinions about this?

You’ll have to excuse any noob terminology or misunderstandings. I am coming here to learn after all :p.

I find, more importantly than Design Patterns, is understanding and following some principles, such as
SOLID and GRASP.

Still Design Pattern should be part of any programmer’s toolbox.

Most importantly, in Unity, I will use the Singleton pattern (it’s easy to create unneeded dependency with this pattern though, so one have to be careful! Taking the time to graph out your app flow and class diagram while following strict principles as much as possible is a great way to avoid that problem!)

In many cases, the Component Architecture of Unity, often takes away the need to use conventional design patterns.

1 Like

Thanks Sluice,

I’ve been mulling over what I originally posted. You may well be right there. Just for piece of mind, what’s your thoughts on some of the frameworks you get on the Asset Store? Like StrangeIOC, Zenject, and things?

Have you ever used dependency injection?

Well after watching a few hours of tutorials it seems that I have been using DI a lot throughout my proj’s without knowing about it. This is my first time really learning DI.

I understand this pretty easily: http://wiki.unity3d.com/index.php/Dependency_injection

So you’ve been using it, is there a reason you feel you need a framework that implements it for you?

2 Likes

Well I’m thinking it might help when designers come up to me asking for big changes later. What I find is I’ll have made about 7+ mini systems (Like UI, enemy spawning/placement, AI, ect), and that they all need to affect code in the overall world, and in their mini systems (UI setups changing between different weapons being held, projectile types knowing the weapon they’re coming from, ect), and when I need to make major changes to certain systems from designer requests, it gets more and more ‘bitty’ to make the changes. I mean it’s do-able, but it shows the flaws in how you’ve designed the code.

I know this means that there’s flaws in my code’s design. I’m thinking that implementing the code through an IoC Container might minimise the dependencies and make my code easier for designers coming up to me and going, “yeah, it’s not a top down shooter anymore, it’s a gummy bear simulator”, or something as mentally challenging lol.

I know that’s a slightly wishywashy answer. The truth is I’m still exploring and don’t completely know whether I definitely need it, or just need to improve my designs, but I’m thinking it might be a good way to improve them. You know?

So really I need a something that makes my game very flexible to being changed later in the day, and extended.

1 Like

I have no experience with frameworks on the asset store.
I like to roll my own way. Following some basic principles as much as possible and design pattern where I see them fit.

I personally don’t really like to be lock in a framework done by someone else, so I tend to avoid it, unless I am somewhat obligated in a project.

1 Like

Yeah I get that. I am kinda the same. I might create a framework of my own out of what they have and use aspects of theirs…

Thanks guys :slight_smile: