- Home /
How to design your code architecture in unity?
Hello everyone,
I have a background in programming (C++, java, objective-c for iOS) and I am new developper in Unity.
I have a hard time figuring out how to organize my code in order to avoid coupling and have a well made, flexible code in Unity.
For example: I would like to manage input for a player. I know how to do it, but where should this be implemented? I know that I'll have a script as a component of the player, but should I make a script called something like "playerInput" that handles only the input or should I put it somewhere else?
This is only an example of the problem I'm facing. Basically, I can't find tutorials or article that give examples of architecture to use in unity.
Do you guys have any suggestion of article/tutorial that could help me understand this better?
Thanks!
EDIT
I have found this web site that describes very well my situation and that may help others understanding their problem: http://www.openchord.org/wordpress/2011/09/unity-and-the-component-model/
In a few words, when you come from Object-Oriented programming, it is not that easy to realise that you are actually working on component-based programming in Unity. Once I've realized this, it does allow for better search on the net and a slightly better understanding.
I believe Unity references should have at least a section talking about their design choice and how it will affect new comers.
EDIT #2
Here are some videos I found that talk about the subject:
http://video.unity3d.com/video/4929872/luug-11-pt-1-of-4
http://video.unity3d.com/video/4929984/luug-11-pt-2-of-4
http://video.unity3d.com/video/4930120/luug-11-pt-3-of-4
http://video.unity3d.com/video/4930121/luug-11-pt4-of-4
However, those are not designed to give a global idea, but only focus on a few specific points.
etbp
P.S. I believe there are way too many basic tutorials that do not take in account the quality of the code they are producing and are focusing on the "wow" effect of having quick results.
I just wanna chime in here and agree that too many tutorials focus on Wow over How. :(
Thanks you very much for the question and the edits - and all of you who answered this. And I agree: I have not yet encountered a unity tutorial for professional programmers.
And I really wonder how I should start with a Unity Game Server architecture...
GREAT question! - Been suffering myself. Although It's component-based design, I'm making my way up using a mixture of both OOP and component design. $$anonymous$$ost the times, I just come up with designs by myself, something that I see makes sense. I always prefer OOP over competence-based.
Posting to agree that many tutorials suck. Cant vote for " un-reputation " ...
Answer by Rogue Adrian · Dec 18, 2012 at 06:50 PM
I've not been programming Unity long, though I've run into many of the same frustrations. It seems like the Unity library is constructed to facilitate a lot of cowboy coding practices, with little or no real encapsulation. The tutorials also tend to have everything as a MonoBehavior or ScriptableObject, where it is often entirely possible to sequester code into a standard C# object without involving UnityEngine, which can help to keep things cleaner.
It seems like the tutorials also use SendMessage() where it isn't really needed - they could have precached a reference to the object/component they're trying to interact with, and use that directly. And it seems like they pretty much never use packages at all, everything shares one big happy namespace.
I understand the general mindset seems to be "Unity for Dummies", making it seem as straightforward as possible to write something that will operate correctly, with no concern for code quality, reusability, maintainability, testability, etc. If you follow the tutorials, and lean on the UnityEngine classes, you'll wind up with a tangled mess of code before you know it. Keeping code clean and well-organized is a struggle you have to put more effort into with Unity than you might with other platforms/frameworks.
I have found a few things to be very helpful:
Minimize your MonoBehaviors. If you can make it a plain C# class, do that. If you can encapsulate functionality into a plain class and reference that from your MonoBehavior, do that. Try to avoid using UnityEngine in your plain C# classes when you can.
Singleton MonoBehaviors can be achieved with a static singleton reference and a check in your Start method: if the static singleton reference is null, set to self, if it's not null, throw an Exception. The only way this would happen is if you have more than one instance in your Scene, so an exception will tell you (the developer) that you've done something you shouldn't have.
When planning your architecture, try to decide ahead of time what you want to be editable in the Unity inspector. Those fields will need to be part of a MonoBehavior or ScriptableObject. Everything else is fair game to place a MB/SO or into a plain C# class.
Likewise, any class that has to run code during a *Update or On* call should generally go into a MB, though you can also define this code in a normal class and call it from MB. The thing to note here is, if you end up having to reference Unity functionality like GameObject from your code anyway, there's less point in encapsulating it in a normal C# class.
Subclassing/inheritance seem to give Unity a migraine - or, at least, using them with Unity gives me a migraine. Any time I try to work with an object hierarchy that I've created with MonoBehavior or ScriptableObject at the top, I wind up wanting to shoot myself. But that may just be due to lack of experience with Unity and/or C#.
I would agree that, in general, the tutorials seem to just cram code in wherever it's most convenient for expository purposes, because nobody has to maintain that tutorial code later. It's also hard to provide general guidelines as every game is different; for example, my current project encapsulates a lot of input handling into it's HUD class, but that might not be appropriate for your game; you might want to encapsulate it into a Controller class or some such. A point-and-click UI will be organized in code very differently compared to a WASD-style shooter, as a matter of course.
Sorry for the non-answer answer, but I hope it helps nonetheless :)
Hi Adrian,
Interesting post. I hope that will help me using good practices.
One thing I'd like to add is that Subclassing/inheritance is problematic in Unity because it is a component-based design. This is quite different from the Object-oriented program$$anonymous$$g. You can read about this if you search component based design or such in google.
etbp
Definitely some good info - I guess I was doing a lot of that kind of component-oriented development already, but every time it felt like a hack/workaround for something that I just didn't fully grasp yet. Good to know I was on the right track, now I just have to go back and re-apply that to the parts I fought with to make inheritance work ins$$anonymous$$d of just going full-force into components.
Answer by Kos-Dvornik · Jul 13, 2014 at 03:01 PM
Use per level singleton to access scene actors.
Use global class state machine and local Animator based states in scripts
Separate Controller from Model-View
[MVC Example in Ukrainian] http://doctrina-kharkov.blogspot.com/2016/08/cultorios-unity-mvc-tutorial.html
[Full Sources] http://kostiantyn-dvornik.blogspot.com/2014/07/anoxemia-unity-2d-tutorial.html
Answer by yoyo · Dec 18, 2012 at 05:26 AM
etbp, that's a huge question. Here's a couple of ideas on the subject of architecture ...
First off, you don't have to put everything into Unity MonoBehaviour scripts, you can have code that's used from your Unity components but uses as much or as little of the Unity API as you like. (For bonus points, if you do this cleanly, you can even unit test your non-Unity API's in MonoDevelop using the built-in unit testing framework.)
Secondly, you can use singletons for systems that there should only be one of. (Or static classes, sometimes simpler.) For non-MonoBehaviour singletons, any standard C# singleton technique will work. For MonoBehaviour singletons you can search the scene for the instance and create it or throw an error if not found. A singleton approach sounds relevant for your input manager.
Since Unity supports most of .NET (.NET 3.5 is generally safe, as of Unity 3.5.6) you can also apply any standard C# architectural techniques for structuring your code, such as the Microsoft Design Guidelines, or this C# implementation of the "gang of 4" design patterns.
Hi yoyo,
I know thats a very wide question, it reflects my low understanding of the Unity code architecture.
For the singleton objects, it seems like a good idea in some situations, but is it really in this case? What if the input your trying to build up needs to communicate with another script, this could be done trough events or delegation, but wouldn't it be rather wierd to communicate directly to another component?
Thanks for the insight
etbp
Our codebase is currently littered with singletons -- too many of them in fact. We've got an input system (singleton) to which we register event callbacks. This makes it easily to isolate all control mappings in one place, but may be overkill for what you're doing. The simplest way to handle input is in an OnGUI method of the "main" component on your player object. Or you could have an input component that does nothing but handle input. Or you could delegate input handling to an associated object (Player has-a InputHandler ins$$anonymous$$d of Player is-a InputHandler).
One guideline (not rule) to keep in $$anonymous$$d -- if a behaviour/feature/function will benefit from being designer-tunable in the Unity Inspector then it should be (or have) a component. If it doesn't need to be tunable (no exposed parameters), then it should probably be a plain old C# class.
Hey yoyo,
I'll try implementing a Input$$anonymous$$anager as a Singleton combined with events callback since this seems to me like highly reusable code.
The way I'm seeing this, I would send an event and pass the keystroke information as parameter (if thats possible). $$anonymous$$aybe I would make different event if it is buttonUp or buttonDown, that sort of things.
The other way I could be using is making an event for each key that I need. However this is less reusable since I may change it for the need of my game. For example, if I use "a" to shoot a bomb, I'll have to add an event specifically for that, etc.
Which do you think would be more appropriate?
Thanks!
etbp
(Sorry, just noticed your question.) I'd have a base Event class, and a derived InputEvent class with whatever fields you need. Possibly a derived $$anonymous$$eyboardInputEvent specific to keystrokes, but probably not necessary. I wouldn't create $$anonymous$$eyAPressedEvent (event per key) but I would consider a ShootBombEvent (which could be posted by the handler for the $$anonymous$$eyboardInputEvent), that is, a translation layer which maps from raw input events (key pressed) to game-specific actions (shoot bomb).
Answer by NicoVar · Feb 07, 2017 at 11:04 AM
Small article I wrote about working with large projects in Unity. Although it does not answer your specific question, it addresses many of the tips given here: http://initiative.online/p/demystifying-unity-for-large-projects-6-rules/
Answer by rolandflentge · Jul 28, 2016 at 01:25 PM
I think this is not a unity specific topic. Its true u have some nice extra features in unity but in my game (huge 2d tile-map, RTS) i use general patterns and practices. Unity is a nice editor but i u want to make your game fancy or keep the complexity in check while your code is growing u need 2 need some more info en tricks.
some nice architectural books : -Game Engine Architecture 1st Edition -Game Programming Patterns Paperback – November 2, 2014
some nice AI books easy to step in books -Programming Game AI By Example (Wordware Game Developers Library) 1st Edition -Behavioral Mathematics for Game AI (Applied Mathematics) Paperback – March 5, 2009
general coding -Clean coding robert c martin -Code Complete: A Practical Handbook of Software Construction, Second Edition 2nd Edition -search on google.com -YAGNI (learn some agile tricks about coding)
Some books are in C++ but u its possible to map those examples to c#/javascript
Further more learn about those nice performance tips from the unity guys.
I am fairly new to game programming (hobby) but i program more than 15 years on businesses applications and how to write those clean an maintainable. Game programming is different but can also benefit from general practices like clean coding, unit testing, managing complexity, Continuous integration.... so these things are also a must to understand and be used in games.
Your answer
Follow this Question
Related Questions
Skills system - class design 0 Answers
Confirm Instantiation or Object Confirm it's Instance 2 Answers
Reliable / intelligent user input handling 0 Answers
Silly question, doing nothing? 4 Answers
Unity architecture 3 Answers