Unity Project Architecture? - c#

I am developing a 2D Platformer RPG Game. The game will have many characters in it, each having different abilities (or powers). My question is that how can I maintain my project structure so that I can add as many charcters or abilities I want to add in the future without making a complete mess of my code.
For example:
I have a charcter lets say Iron-Man so I want him to use thrusters but let say there is another player using Captain America as his character who cant use thrusters.
Now how to make a system so that I can add characters and abilities or have characters exchange any ability with another at runtime?
I've heard about using interfaces to make code cleaner and also about using scriptable objects but I haven't quite worked with them.
I would like to know a concrete method of making this type of system (If there is any).
Any links to tutorials would be appreciated.
PS- My game has just 1 character in it and everyday I open my project hoping that I will add a new character but I am always afraid that I will break my code and I think that if I surf a little more on the internet I will get a proper sturcture to start with so I dont take any risk and I just end up changing some things here and there and close it.

A few things to check out (Mainly related to OOP):
SOLID design and Design Patterns Videos
https://unity3d.college/2017/11/24/solid-unity3d-code-architecture-open-closed-principal/
https://www.youtube.com/watch?v=FGVkio4bnPQ
https://www.youtube.com/watch?v=UoNumkMTx-U
Lots more in his channel, those were just a few
Design Patterns Code to study
https://github.com/Naphier/unity-design-patterns
https://github.com/QianMo/Unity-Design-Pattern
Lastly:
Unity's Free (For next month or so) learning: https://learn.unity.com/

Related

Are there best practices for "Singletons" (persistent GameObjects) in Unity?

I'm rather new to Unity, and C# too as a matter of fact!
What I am doing right now is:
I have a "Singleton" (it's not really a Singleton but that's not the point) GameObject called GameManager, to which is attached my GameManager.cs script containing most of the game info (which tutorial text has been already displayed, functions to load localized text, last scene loaded...)
As children of this GameManager object, I have different kinds of GameObjects I do not want to destroy on load either, such as PostProcessing Profiles, Global Lights, Audio Manager, UI Canvasses (canvi?) and other things...
There are plenty of great tutorials on Unity, and it's an awesome community, but I could not really find any info on Unity's "best practice" regarding GameObjects management.
Is this a correct way to proceed? Will I have issues in the future with this method? Should I make a generic class that implements Unity's DontDestroyOnLoad() and have the Object I want to keep inherit from that class? Is there a better way?
It works fine for now, but I want to be sure I am not doing this the wrong way and potentially messing up with my game's performance or stability.
Many thanks in advance.
There are two best-practices here.
Build lots of singletons, and replace Unity's built-in initialization system
Build very few singletons, and work within Unity's initialization system, and make heavy use of the new Multi-Scene Editing system.
Option 1 is very popular with game-studios and professional gamedevs, who are skilled at doign this and have done it many times before. The main problem is that once you start down this route you are comitting to maintaining your own parallel init system. The main advantage is that your system is probably better, definitely more powerful, and usually faster (!) than Unity's internal one.
Option 2 is more popular with people new to game programming, who want to lean on as much of Unity's built-in features as possible.
That said, there are some strange things in your question.
For instance ... Canvas? Why on earth would you be trying to make Canvas into a singleton? This suggests you're misusing Canvas in a big way (and probably some of the other classes).
The standard approach (and the only one that Unity supports) is for every Scene to have its own unique Canvas. To do something different ... is very odd.
I suspect you've misunderstood what "DontDestoryOnLoad" does. It does not prevent things being destroyed on load!
Instead, it prevents being destroyed when a NEW scene is being loaded, and they only lived in the OLD scene. A much better name would have been: "DontDestroyWhenLoadingANewScene"
There are a lot of bugs (going back many years) in Unity with DontDestroyOnLoad, so in general its best to avoid it as much as possible. For simple cases it works fine, but if you use it too much you run into complex edge cases and interactions with Unity's own internal classes.
Obligatory utopic programmer answer: Try to avoid using singletons as much as possible.
That being said, feel free to use my singleton implementation, been using it for years in production and it works fine.
https://gist.github.com/ronrejwan/7a4f0037effec3c9e8943542cf9cfbc9

The concept of classes is ok if i have a single user application and i work alone at it and just i'll use it?

I make an app in c# with windows forms and all my code is behind the window code, so i have for now 2500+ lines of code and some of my collegues say to use classes to divide the code by functionalities but i don't find a purpose in that because everything will be made public and so on.
None of them know to explain me why it is the best approach, but just give me vague hints like : "if you do a modification somewhere your other functions will crash" and i don't know how that is possible...
I searched and find a keyword "partial" so what should i do? Should start learning classes and so on?
You need to go right back to the basics, and not be put in charge of writing an application by yourself. Ask your employer to excuse you from your responsibilities whilst you learn how to do them, you're just digging yourself a deeper hole with every line of code you write at the moment.
A class is designed to be a reusable block of code. the class is for relating functionality together. the class is for classing things into a particular set of instructions.
This is the idea and reasoning behind OOP.
Consider a Road, a Road can have 0 to x cars on it. All of the cars can "drive" and they can "turn" they can even leave the road and join another road. They work together but are not one and the same thing. A car can drive but a road cannot. You dont want to have a "Road" class with 900000 methods for different cars all with their own drive methods and "leave road" method... You have 1 "class" which you can create multiple times into different occurances of that class, which may or may not be on that road.
Not to labour the analogy but it's a very popular one. Your code is not all doing the same thing even if you think it is, You have to scope your opinion correctly. You may have file access code next to UI code next to Business logic code next to network communication code. they are all pieces in the puzzle of "My Application", but within "My Application" they are not doing the same thing. It is with this kind of thought that you need to move forward and not with "It's just me, Writing this same application, it all goes here"
The main answer for which you should divide your code into classes is code reusability. You could greatly benefit from techniques of object oriented programming such as inheritence, polymorphism and so on.
Moreover, the time invested in learning Object oriented programming is a time invested in you, and for your greater understanding of different programming languages or frameworks which you may be using in the future.
Although you could do this project all by yourself and without using any classes, I strongly recommend you to try and learn OOP programming.
PS: C# is an object oriented programming language, which means that all object and variable type you may be using are classes!

How to write in C# a chess like game?

I have a question. I want to write a chess like program applying the rules as follows:
It should have just a king and a queen on one side and the other side should have just a king.
The first side should mate the second side with the lowest number of moves possible.
I want to know your thoughts about how to make this project. For example I want to know about which way of writing code is easier (object oriented or structured, ...) (I have a little information about object oriented) and can say me about writing its algorithm? For example from where I should begin to write the codes?
The good news here is that your problem is quite restricted in scope, as you only have three pieces to contend with. You're not really implementing a game so much here, as solving a logical puzzle. I'd approach it like this:
Figure out how to represent the three pieces in a simple way. You really don't need a UI here (other than for testing), since you're just trying to solve a puzzle. The simplest way is probably a simple Row,Column position for each of the three pieces.
If you haven't written an object-oriented program before, you'll probably want to stick with a procedural model and simply define variables for the data you'll need to represent. The problem scope is small, so you can get away with this. If you have some OOP experience, you can split up the problem appropriately, though you probably won't need any inheritance relationships.
Write the code for generating possible moves and determine whether a given move makes any sense at all. A legal King move is any move that does not check the King. Most queen moves should be permissible, but you probably also want to exclude moves that would allow the enemy King to take the Queen.
Now you need to determine a strategy for how to put together a sequence of moves that will solve the puzzle. If you need to find the true optimal solution (not merely a good solution), you may need to do a brute-force search. This may be feasible for this problem. You'll probably want to perform a depth-first search (if you don't know what this means, that's your first topic to research), as once you find a possible solution, that limits the depth at which all other solutions must be considered.
If you can get brute force functional and need to make things faster, consider if there are moves you can prove will have no benefit. If so, you can exclude these moves immediately from your search, saving on the number of branches you need to consider. You can also work to optimize your evaluation functions, as a faster evaluation is very beneficial when you are doing billions of them. Finally, you might come up with some heuristics to evaluate which of the branches to try first. The faster you can converge to a 'good' solution, the less cases you need to consider to find the optimal solution.
One side note I realized is that the problem is very different if you assume that the enemy King is trying to avoid checkmate. The simple depth-first pruning only works if you are allowed to move the enemy King in the way that best checkmates it. If the enemy King is attempting to avoid checkmate, that complicates the problem, as you have conflicting optimization goals (you want it to occur in as few moves as possible, yet your enemy King wants to postpone as long as possible.) You might be limited to characterizing a range of possibilities (say, 3 moves best case if King is perfectly cooperative, 8 moves best worst-case if King is perfectly evasive.)
Take a look at this SO question (Programming a chess AI).
From the answers to that question, I think this C# Chess Game Starter Kit would be a good start, but I would also look at the other articles referenced as well for some interesting history/information.
This is the simplest possible example of an endgame database. There are less than 64^3 = 262144 positions, so you can easily store the score of each position. In this case, we can define the score as the number of moves to checkmate, for a winning position; or 255 for a drawn position. Here is an outline:
Set all scores to 255.
Look for all checkmate positions, and score them as 0.
Set depth = 1.
For each drawn position (score=255), see if a move exists into a won position (more precisely, see if a move exists into a position from which all of the opponent's moves are losing.) If so, set its score to depth.
If no new position was found in step 4, you're done.
Increment depth, and go to Step 4.
Now you have a 250k table that you can save to disk (not that it should take many seconds to generate it from scratch). If space is important, you can reduce this significantly by various tricks. Wikipedia has a nice article on all this -- seach for "Endgame tablebase".
A poster here suggest that Stockfish would be a good start, but it is a C++ project, whereas you are asking for C#.
The solution depends on your requirement. If you are interested in "just make it work", you could complete the project without writing more than 200 lines of code. You could embed an open source C# project, and ask the engine to report you the number of moves to mate. If the open source project is UCI supported, the following command will do the job:
go mate x
where x is the number of moves to mate.
However, if you need to do the thinking yourself. You will need to choose between efficient bitboard or object-oriented representation. Bitboard is a much better representation, it is very fast but harder to program. All chess engines use bitboard. In your project, represenation efficiency is not too much of concern, so you could choose OO represenation.

Patterns: Render engine allowing editor integration?

I am trying to determine that if (before I start) on a new project I can pick some suitable patterns which will help with development as the project gets more complicated.
The Scenario
To have an application that draws 'simple' lines on the screen. Ideally encompassed into a 'Render Engine' which I can package into Silverlight, WPF demo applications etc.
I also require editor application that uses the render engine to do the bulk of the displaying, however provides additional functionality like control points for moving the lines about the screen & Dialogs for changing the colours of the lines etc.
The Goal
To keep the render engine specalised and efficient. The editor should be able to 'inject' the additional functionality (i.e. display of control points) into the objects used by the rendering engine, or into the render engine itself. I don't want to code any editor specific code into the render engine.
My thoughts so far
I'm thinking of using an encapsulation/template pattern for the objects that will be used by the rendering engine, somehow allowing the editor application to supply a class to the object which 'tacks on' the functionality for the control points (and for example the event handling for moving of the control points).
My reason behind liking this idea is that the rendering engine never need know about the environment in which it is working. The editor can be changed extensively without ever having to change the rendering engine (hopefully).
But....
I may be wrong, if anyone can see any pitfalls, or has experience of better ways to tackling this problem I would love to hear them!
I agree with Charlie that you should start with a simple design prototype and extend it as needed (that's how I started with my map rendering engine). I can give you a few suggestions though:
Separate the drawing engine from the rest of the code (here's an example how). By the drawing engine I mean the code that actually draws something on the screen/bitmap. It should consume drawing primitives, not some higher-level entities. This way you'll be able to switch the drawing engine easily (example: SVG, PDF, GDI, WPF...)
If you want to have an editor, one of the patterns that are useful is the State pattern
Well shoot, that's an impressive amount of forethought.
My philosophy has always been, use a design pattern when you need to use one. Otherwise you may become an architecture astronaut, designing grand schemes all for naught. It's good that you're thinking about design before development, but really, how much can you possibly know about the project before any code has been written? Just about nothing. And if you force yourself into a pattern before any code has been written, you may end up jamming a square peg into a round hole for the entire lifecycle of the application.
My advice to you: write a prototype first. Quick and dirty. No real design; just make a skeleton that walks. Learn from it. If you thought of a better way, scrap the original and redesign a new one. Use design patterns that make sense as you add functionality, not for the sake of adding functionality.

What Should Be in a 2D Game Engine? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Ok, so I ended up writing my own game engine based on top of XNA, and I am just wondering what else I need to make a complete engine.
This is what's in the engine:
Physics (Farseer Physics)
Particle Engine (Mercury Project)
2D Cameras
Input Handling
Screen Management (Menus, Pause Screen, etc.)
Sprite ( Animation, Sprite Sheets)
And XNA stuff like Sound.
Am I missing anything that might be crucial to a game engine?
You're approaching it in an upside-down manner.
What should be in your engine is the following:
All the code that turned out to be common between your first and your second game.
First, write a game. Don't write an engine, because, as you have found out, you don't know what it should contain, or how it should be designed. Write a game instead.
Once you have that game, write another game. Then, when you have done that, examine the second game's code. How much of it was reused from the first game?
Anything that was reused should then be refactored out into a separate project. That project is now your game engine.
This doesn't mean that you shouldn't plan, or shouldn't try to write nice code. But make sure you're working towards something concrete, something where you can tell a good implementation from a bad one. A good implementation of a game, is one that works, is fun, and doesn't crash. Write your code to achieve those things first.
A good implementation of an engine? That's trickier. What's a good implementation of a renderer? Of an AI framework? Of a particle system? Ultimately, the only way to determine whether you have a good engine is by seeing how well it works in an actual game. So if you don't have a game, you have no way to evaluate your engine. And if you have no way to evaluate your engine, you have no way of judging whether any of the code you're writing is actually useful.
A theme or market for your engine. If you're doing anything beyond basic your basic graphics engine, you'll want to concentrate on a market for your engine, like RPG, strategy, puzzle, platformer, action, or FPS (ok, not FPS).
This will help you point yourself in the direction you need to go in order to make further enhancements to the engine without asking us. An engine like say, the Unreal Engine, can do multiple things, but what it tends to do best is what it's made for, FPS games. Likewise, you should tailor your engine so that it suits a particular field of interest, and therefore is picked up for that type of gameplay.
You can make it general to a point, but realize the more generalized your engine is, the harder it is to program, both time wise and skill wise. Other programmers are also less likely to pick up a general engine (unless that's all there is) if a more specific platform is available. Or to just write their own since modifying a generalized engine is about as hard as creating your own.
A few more things:
Path finding - very useful for AI
AI - possibly - depends on how generic you want the engine to be.
High scores
Replays - makes high scores much more interesting, as you can actually watch them.
A couple ideas:
Artificial intelligence (perhaps just simple AI utilities, like pathfinding algorithms)
Saving all or part of the game state (for suspending and restarting at a later time or saving high scores).
I think that you covered the general requirements of a 2D engine. The only thing I would miss in that list would be:
GUI Library
Also to make development processes easier:
Script Engine (LUA, C#Script, ...)
Dynamically Refreshed Assets (see Nick Gravelyn's Blog Entry)
You might also add another layer on top of XNA's existing stuff:
A quite bareboned Network/Lobby implementation
More abstract handling of multiple controllers (DropIn/DropOut during gaming sessions, like see Resident Evil 5 Coop) - maybe event-based
Finally you might add some "ready2use" shaders. Maybe get some inspiration from the discontinued FaceWound (from the "Garry's Mod" developer).
It depends on the game, but another thing often needed is a good networking framework.
Many modern games, including 2D games, seem to have some form of networking in place.
Animation framework so that you can say: take this sprite, move it in this direction, folowing this path using this speed, acceleration and such
Basic GUI system. Don't implement a whole Windows, but basic things like a pointer and a button, and such - keep it basic
Debugging component for displaying FPS, numbers of sprites and such
Also a good thing is to make some games, and then you will quicky see what things you repeat doing for each game, and then look into how to can get that into the engine.
2d lighting system is a good advanced feature. You can use Krypton for that.
Map editor. Or even better support any tile-map format, compatible with "Tiled Map Editor". So you can just use Tiled.
Scheduler/Timer for game actions.
Screen wipe effects such as page turn, fade out, etc. to make nice transitions between screens.
Game layers with build in parallax would be usefull too.
In game console to process commands or scripts without restart.
Easy load for texture atlas as sprites or animation.
Nice Work,
We (me and some of my friends) are working on a game engine too actually,
We've already got all what you mentioned but moreover we've got the following.
audio manager : a simple class to handle background music and sounds
effects in XNA.
video manager : it's not complicated, a simple class to handle video
playing in XNA.
effects manager : is responsible for stuff like bloom, blur,
black/white colors .. etc.
Good Luck :)
3d Acceleration should be in a 2D engine.
Using the 3d hardware that most people have these days is the best way to get amazing performance for your 2D games...
Good collision detection is very helpful. If you implement it efficiently, it really reduces the time required for every frame. Besides that, in my engine (for Pygame) I have a method of separating the main screen into a number of subscreens, which I find useful.
Depending on the target game type, include Navigation Graph(s) with node and edge annotations. (Good for many games, but not so much for the token side scrollers that are made with 2D graphics engines)
A component to generate them (via a flood fill algorithm).
Be sure to include all of the major path finding/planning algorithms (A*/Dijkstra/etc.) to traverse those graphs.
The pitfall of this is that you will have to define what a 'map' is for the engine, which might limit users of the engine.
Related things:
Location based triggers (player enters an invisible circle and something happens - queue cutscene, start ambush, etc.). I would say provide a base class for the trigger and implement some basic ones to show how it's done (ie. weapon pickups etc.)
Some game engines implement networking (though this is kind of part of the 'xna stuff')
The most useful thing to include above all else would be tools to easily use your engine. Maybe use your engine to create the tools. I'm sure you would find a lot of flaws that way.
Simple pixelperfect collision detection. NOT Farseer Physics. Simple drawing routines like drawline, drawcircle etc.
A tile repeat tool. Something that allows the user to add/create a tile, and manipulate the edges for a smooth repeath pattern.
Um. This list is an "internals" list. To make great engine is to make great "external" list.
Look at UE3 for example -- it is here because of great tools. You need tools for world creation, to create optimal packages of resources (it should be in internal list too ;-)), for collision object specification etc.
Plus, to add to Organiccat answer you should decide on tech level. You can go for simple sprites or you can want fancy effects (so shaders are needed, and with this you need infrastructure)

Categories

Resources