• Advertisement
Sign in to follow this  

Unity Advanced game structure

This topic is 1277 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi community,

 

I have finally decided to start my first big game (2D RPG with everything like quests and so on). So I need a good way to structure my code, not to end in a chaos like in some of my other projects. So I googled a bit and found different patterns for object handling like Observer, Mediator or event queue. So I wanted to ask you guys if someone has experience with different patterns and can tell me which to use, why to use and mybe an example when to use. Sry for my english, I am from Austria.

 

Have a nice day :D

Share this post


Link to post
Share on other sites
Advertisement

Thanks for your reply, which showed me that I have to think more about structure and upcoming problems, than I thought. I´m often impatient and always start programming before I have a solid structure to build upon, which leads to the chaotic code. So I´m going to think things over. I have already some ideas when I can use patterns. I thought of a Command pattern for player input and contolling enemies with an AI controller. That would let me easily attach the player actions(attack, ...) to Keys or MouseButtons. So would that be a good way to start? And I also have some ideas where to use the observer pattern(Achievment system, SoundManager, ...). But one problem I actually have,is that I want an easy way to add interaction between the player and world objects like treasures, enemies, traps, NPC´s and so on. I thought of an event pipeline(for example the player fires an event before he moves and objects like the collision layer or doors would react to that and would prevent the player from moving). So what would be a good approach to solve that "communication" problem. I thought of using the Observer pattern here as well, but I am not sure about that.

 

Thanks for your help anyway :D

Share this post


Link to post
Share on other sites
... I thought of a Command pattern for player input and contolling enemies with an AI controller. That would let me easily attach the player actions(attack, ...) to Keys or MouseButtons. ...

The Command pattern, if you mean exactly those of the Gang of Four, is overkill in this case. It is fine to abstract input (in the case of the player character) and to "objectize" any character action, and the Command pattern goes in that direction. However, other features of the pattern are not so good in this case. You usually don't need a history of past commands (no undo, and usually no playback). You will not queue up commands, waiting for the previous ones to complete (because players will claim that your game is not responsive). You will not perform the actual action in some virtual Command::perform().

 

On the other hand, if you understand Command as a lightweight instruction for interpretation by e.g. the animation sub-system or whatever, then it's okay.

 

... But one problem I actually have,is that I want an easy way to add interaction between the player and world objects like treasures, enemies, traps, NPC´s and so on. I thought of an event pipeline(for example the player fires an event before he moves and objects like the collision layer or doors would react to that and would prevent the player from moving). So what would be a good approach to solve that "communication" problem. I thought of using the Observer pattern here as well, but I am not sure about that.

This is a real problem per se. You have to notice that the observer pattern introduces some kind of local view onto the world state. What I mean is that a single event happening in the world is seen by the observer at the moment it is generated, but it does not foresee all the other events that happen at the same simulated time but at a later runtime due to sequential processing. So the observer reacts on a world state that is incomplete! 

 

Look at the structure of a game loop and notice that it is build with a well-defined order of sub-system processing. Introducing observers often will break this well-defined order (for example the animation sub-system moves the character and the collision sub-system moves it back).

 

This is one of the examples where the problem analysis need to take into account the big picture. Observers are fine for desktop application where the entire UI is just reacting on events, but a game is (usually) a self running simulation.

 

In short: I would not introduce observers especially wherever sub-system boundaries are crossed, and I would think twice for observers in general.

 

 

Just my 2 Cent, of course ;)

Edited by haegarr

Share this post


Link to post
Share on other sites

In preparing for battle I have always found that plans are useless, but planning is indispensable.

 

Dwight D. Eisenhower

Share this post


Link to post
Share on other sites

Ok, so what would be a good approach to decouple all the different parts of a game(Physics, Collision, Events), so that there´s no code of collision detection in the player class itself, or to decouple the achievment system from parts like physics(for example I want an achievment "Fall 100 metres") then I would use observer to let the achievment system

listen to the physics part. Till now I always used Lists of Gameobjects for exampe. So when I shot a bullet I added it to an ShotManager and Updated it in there. Same with collisions, I had a collision manager which had references to the player, shotmanager and then checked tif they collide. But I don´t want that ugly coupling anymore. I want a flexible architecture to work with, so that I can easily expand the game.

There is a interesting way to handle this problem, but I don´t know if it´s too slow or not manageable(the first answer): http://stackoverflow.com/questions/11323413/handling-interaction-between-objects    

 

I also read about putting everything in a class and let an entity have a list of behaviours(like movingPart, physicsPart), but I don´t have experience with that kind of architecture so I want to learn it first before I try my luck in a game.

 

So what approach would you choose?

Share this post


Link to post
Share on other sites

One thing to keep in mind is to keep classes small enough and short. May be hard to follow, but typically large classes may be a sign of a code bloat and that they may have too many responsibilities.

 

Cheers!

Share this post


Link to post
Share on other sites

Yeah that has been my problem so far, but my last project was better in that point. Still I have to find another way of handling the objects in a growing project.

Any approaches? How manage you guys your game objects?smile.png

Share this post


Link to post
Share on other sites

There's no right answer to these questions, but the most important thing is that you're asking the questions and thinking about it.

 

In the case of collisions what I might do sounds pretty similar to what you've described doing in the past.  In Java, I would create an interface called "Collidable".  I would then keep track of all of the Collidables in a list (where list could be an ArrayList, HashMap or whatever's appropriate) and perform collision checks on the objects in that list.  If you want to get more fancy you can have your list hold WeakReference objects so you don't have to worry about destructors (but now we're getting into Java specifics, and you haven't said you're using Java).

 

As far as your achievement system, you may be able to find some fancy way to abstract it and provide complete de-coupling.  But sometimes the best thing to do is just:

// TODO - move this into a framework later
doUglyAchievementCheckInPlayerClass()

And then if "later" never comes, it probably means you've better spent that time on some other part of your game.

Share this post


Link to post
Share on other sites

Thanks for your answer. I am using C# (XNA) so I don´t have to care about Destructors like in C++. Your way to handle collisions is the only way I know so far and therefore the one I am also using. But how do others handle collision(also tilemap) without having everything coupled? When looking in the internet, I only find things like quadtrees, ... , but I am interested in way different objects communicate in a game. What about that approach(first answer): http://stackoverflow.com/questions/11323413/handling-interaction-between-objects. As I said above I want to make a RPG, not too big but still that it looks and feels like a classic RPG. So now I am planning things and one problem that occured is, that I want a way to interact with game objects(treasures, traps, obstacles like stones, ...) without having coupling(or at least not much coupling) between the different classes, so that I can reuse parts of the code in other similar projects. Once again sorry for my english. 

 

Thanks for your help so far :D

Share this post


Link to post
Share on other sites


haegarr how do you handle interactions between different game parts/objects?

This cannot be answered in a sentence except with "it depends" ;)

 

 

BTW: Don't think that I reject the use of Observer principally. All things have their use, even Singletons, but only at the right place.

 

 

I'm using a game loop in which sub-systems are updated in a defined order. This is, as said, not uncommon. I like to hint at the chapter of Jason Gregory's book that can be found as excerpt at Gamasutra. With such an approach each sub-system knows that the state of the world at the moment of its own update is complete with respect to all the sub-systems prior in the loop. For example, all animations are already run before collision detection is invoked. If collision detection would be invoked when only a part of the animations were run, then it may detect false collisions simply because some of the Placements are still set to their obsolete position. Later on, when rendering takes place, the rendering sub-system takes all Placements as they are. It is not interested in how many "change events" would have occurred; it is just interested in the current state. In this example states are written and read but no notification about state changes are made.

 

Another example is input processing. I do not propagate input events into the various sub-systems. The Input sub-systems knows of its devices, gathers / collects all available input state changes, timestamps and unifies them, and puts them into a queue (this process is not part of the game loop because the Input sub-system runs in a thread apart from the game loop). When a sub-system in the game loop is interested in input, it has to investigate the said input queue when it is called for update, detect input situations matching the own input configuration, and react accordingly. Here the input state as well as state changes are memorized (for some time, e.g. allowing for detection on input combos), but no notifications are made.

 

Another example is the implementation of the sense system. This is part of the AI sub-system where visual, aural, touch and even olfactory stimuli are produced and may be detected by AI (usually of NPCs). Some visual and aural stimuli are generated on-the-fly when the AnimationServices is updated. Other stimuli, also visual but also olfactory, last longer. Every existing stimulus is linked in a spatial structure where the AI components can query for collision with their respective senses. Also here the occurrence of a new stimulus is not notified.

 

That said, low level services like the SpatialService manage low level data like the Placement (btw, for game objects I'm using a component based entity architecture with sub-systems, although they are called "services"; just for the case you don't have assumed it already ;) ). Higher level services query lower level services for data, e.g. the SpatialServices provides queries for collision, proximity, and line-of-sight. The lower level services do not know how to deal with the results, that is the job of the higher level services. Hence there is a strict top-down coupling.

Share this post


Link to post
Share on other sites

Wow thanks. That was that kind of answer, which is helping a lot. I also read the article at Gamasutra, which is sometimes a little bit hard to follow, but I understood what the author meant, I think. But such a type of structure is too professional for me I think at that point(I am game programming one year now), and I think I will go with a different, easier approach. Even all the questions didn´t really solve my problem with the RPG, it helped a lot. Thanks for all your patient and interesting answeres. I think I am going to start a new thread for my question about the RPG.

 

So have a nice day :D

Share this post


Link to post
Share on other sites


I also read the article at Gamasutra, which is sometimes a little bit hard to follow, but I understood what the author meant, I think. But such a type of structure is too professional for me I think at that point(I am game programming one year now), and I think I will go with a different, easier approach.

Many game loops are not so complex like the one shown there. However, it is important to understand that there is a defined order of updates, regardless of how many steps your loop has. That is done in all game loops I know of.

 

Traditionally one does something like the following: At the beginning of the game loop run the input sub-system (which is in that case not running in its own thread, of course) to collect input, then run AI if necessary, then run animation, then run rendering.

Share this post


Link to post
Share on other sites

Yeah. I do it that way you explained it, but I handle animation and AI inside the respective classes(for example in a platformer I have a class AnimationStrip and every animated objects has a dictionary(C#) with strings as keys(so I can say currentAnimation = animations["jump"]) and AnimationStrips as data. So would it be a good idea to put that all into one sub-system? And I let every object draw itself,so that I can say for example:

 

foreach(GameObject o in gameObjects)

{

     o.Draw(spriteBatch); //Spritebatch is used for drawing in XNA

}

 

so but thats ok or?

 

Thanks a lot for your answeres :D

Share this post


Link to post
Share on other sites

I now have a new idea to tackle that problem with interacting with world objects(treasures, ...). I simply add triggers to my map and when the player is near a trigger he can press a button assigned to interacting with objects(lets say space) and then I simply fire an event assigned to that object(for example when interacting with a sign a dialogue window opens). So would that be a good idea?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By eldwin11929
      We're looking for programmers for our project.
      Our project is being made in Unity
      Requirements:
      -Skills in Unity
      -C#
      -Javascript
      -Node.js
      We're looking for programmers who can perform a variety of functions on our project.
      Project is a top-down hack-and-slash pvp dungeon-crawler like game. Game is entirely multiplayer based, using randomized dungeons, and a unique combat system with emphasis on gameplay.
      We have a GDD to work off of, and a Lead Programmer you would work under.
      Assignments may include:
      -Creating new scripts of varying degrees specific to the project (mostly server-side, but sometimes client-side)
      -Assembling already created monsters/characters with existing or non-existing code.
      -Creating VFX
      -Assembling already created environment models
      If interested, please contact: eldwin11929@yahoo.com
      This project is unpaid, but with royalties.
       
      ---
      Additional Project Info:
      Summary:
      Bassetune Reapers is a Player-verus-Player, competitive dungeon crawler. This basically takes on aspects of dungeon crawling, but with a more aggressive setting. Players will have the option to play as the "dungeon-crawlers" (called the 'Knights', or "Knight Class", in-game) or as the "dungeon" itself (literally called the 'Bosses', or "Boss Class", in-game). What this means is that players can choose to play as the people invading the dungeon, or as the dungeon-holders themselves.
      Key Features:
      -Intense, fast-paced combat
      -Multiple skills, weapons, and ways to play the game
      -Tons of different Bosses, Minibosses, creatures and traps to utilize throughout the dungeon
      -Multiple unique environments
      -Interesting, detailed lore behind both the game and world
      -Intricate RPG system
      -Ladder and ranking system
      -Lots of customization for both classes s of customization for both classes
    • By RoKabium Games
      Custom coffee mugs have arrived... More caffeine!
      Have a great weekend everyone! 
      #gamedev #indiedev #sama #caffeine
    • By Atwo Studios
       
      Hey guys,

      Anthony here from Atwo Studios bringing you some new updates for the new year!
      In this video I go over our game ROY, the new games and some general updates to the company!

      If you have not checked out ROY feel free to give it a try! Many people have said they enjoyed the game thus far!
      ROY: https://goo.gl/o6JJ5P
       
    • By Affgoo
      https://play.google.com/store/apps/details?id=com.NE.Alien
      still a lot of work to do, but its pretty stable  please let me know what you think <3
      Atlas Sentry is a game of destroy everything. Using your turret, simply swivel and shoot your way to victory, upgrading your weapons to unleash destruction on the variety of spaceships. The bigger your combo’s the more score you get! Earn silver as you play and then purchase new weapons and abilities to better deal with your enemy. Different enemies use different tactics and weapons, work out your own priorities in their destruction order. 

      Features: 
      **2 different game modes 
      **A level select mode with 20 difficult levels including a final boss, can you defeat it? **Arcade mode of endless destruction, how long will you last? 
      **High scores to compete against others, see who can take the top spot. 
       
    • By Chamferbox
      Chamferbox, a mini game asset store has just opened with some nice game assets, 
      Here you can find a free greek statue asset 

      Also check their dragon, zombie dragon and scorpion monster out:



      They're running the Grand Opening Sale, it's 30% off for all items, but for gamedev member, you can use this coupon code:
      GRANDOPEN
      to get 50% off prices What are you waiting for, go to
      http://chamferbox.com
      and get those models now!

      View full story
  • Advertisement