Jump to content
  • Advertisement
Sign in to follow this  

Unity Special Rules in a Turn Based Entity Component System

This topic is 1981 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



I'm currently planning on implementing a tabletop game in the spirit of Warhammer 40k.

This is a turn based strategy game with lots of special rules.


Why a entity component system?

  • Units have special ability, which could be realized each as a component
  • Area effects such as fear, could also be realized as a component indicating that a unit is affected by fear
  • Each race or army type have there own special rules
  • Special rules generally only effect some part of the system, e.g., movement or shooting
  • Ease of integration in Unity (make games not engines wink.png )

So what is the problem?

How to realize the special rules?


To perform an action two six side dice are rolled and the sum is compared to a threshold.

Lets assume a special ability or effect that modifies this test as follows: instead of two dice three dice are rolled and the highest result is discarded.

Another effect might case that an additional dice is rolled and added to the result.

So the combination would be: roll four dice remove the highest and add the rest up.


So in a perfect world the rules do not have to know about each other.

But should be able to override each other such that an ability can cancel out an effect.


Would you ...

  • implement the abilities as flag components? And put there effect into each system, e.g. shooting or movement system?
  • put the logic of the ability into the components?
  • have the logic of the ability as another component, where one could have many components of the same type, if the effects can stack?
  • any other ideas?

Of course if you are missing an information please feel free to ask. Also I'm looking forward to suggestions of different approaches.

Share this post

Link to post
Share on other sites
This is just my personal take, but it sounds to me like you really want to write a component system but don't actually know why they are useful or when to use them. Your reasons are square peg/round hole to the extreme.

I think you've picked the wrong tool for the job, or maybe the wrong job for the tool.

Share this post

Link to post
Share on other sites

Very well then.

But what would be the 'right' tool?

Which would be the 'right' method or pattern to use in the above sketched example?

Share this post

Link to post
Share on other sites

Well, if I'm reading you correctly, it seems the issue you have is with event communication.


The "Event" that is occurring is a dice roll.

Ignoring everything else,  the event taking place is a dice roll.


Now, from what you describe, there are a number of dice-roll types that can occur.  2-dice, 3-dice-subtract-lowest, 4-dice, etc.

Those events must be communicated to all interested components.  The most generic way to do that is to broadcast the type of dice-roll, and then the dice.


Broadcast(4-DICE-ROLL_ENUM, 6,3,2,6)  //where the enum tells what kind of roll, and the 4 numbers tell what the rolls were.


You can package the message up in a million different ways, the important part is entities and/or their components need to hear about it, and react by changing their internal state, and/or sending out their own messages.  One of the entities/components may score that roll as a hit, and set it's internal state to dead, while sending out a "Died" broadcast message to all the other entities/components.


So, to directly answer your question, I guess you would say you "put the logic of the ability into the components".  Because they have to deal with these events as they see fit.

Share this post

Link to post
Share on other sites

[quote name='ApochPiQ' timestamp='1358372763' post='5022315']
Composable rule systems


Thank you very much!


I'll look into your suggestion and will report back on my progress.

Share this post

Link to post
Share on other sites

I think your problem is just reducing the complexity by separating those dice throws from interpreting them. Why not make make some simple classes to do them and then have each component which needs a different algorithm use its own different instance of that? For example like this:


class Dice {
  Rng& rng;
  int sides;
  Dice(Rng& rng_,int sides_);
  int DoThrow() { return rng.GetNumber()%sides+1; }

class DiceThrower {
  // some variables to remember how to calc all the throws
// ...
  int DoThrow();

class Component {
  virtual ~Component() {}
// ...
class MoveComponent:public Component {
// ...
class ShootingComponent:public Component {
// ...

Share this post

Link to post
Share on other sites
If you can give me any good reason whatsoever to write that code in a "component" style instead of just providing a DiceThrower class and using it simply and sanely, I will buy you a six pack of the beverage of your choice.

Share this post

Link to post
Share on other sites
If you can give me any good reason whatsoever to write that code in a "component" style instead of just providing a DiceThrower class and using it simply and sanely, I will buy you a six pack of the beverage of your choice.



Ok, I can't do that.    But was thinking about a similar problem for my hex-based war game.   Where like the question above each unit-class can have special rules that exempt them from the "normal" base rules.    Now this can be more complicated that just the number of dice.    To give two different examples...

ALL units move at 6 hexes per turn.    Well except a select number of fast units.   They move 7 per turn.

ALL units calculate attack damage with "formula Y".   Welll except for "maulers" which use "formula Z".

and so on...


Initially I thought about just making those flags in my unit data table and the code would just check the flags and deciede what to do.    With all my recent reading though it seemed like a componet system might be a nice way to handle this.


I think (please correct me dragongame) this is similar to what the orginal question was about s/he just gave the dice throws as an example.


So based on that is going the componet route just overkill?

Share this post

Link to post
Share on other sites
Component systems are a very specific tool for solving a very specific problem.

To wit: components solve the case where you have a lot of common functionality that needs to be recombined in an unpredictable number of combinations, but with consistent rules as to how the combinations should work. A classic example would be building cars. Every car is a collection of a drive train, wheels, body, accessories. A component system lets you assemble a car from any combination of the requisite kinds of parts. I can come along in 6 years and assemble a totally new type of car just by combining the latest and greatest version of each part. The whole totality remains a car; if I want to change gears and start building houses, I need different code. But so long as what I'm building is still a car, my component model serves me well.

What it sound like you want is just a data-driven architecture. A unit has some properties: how many hexes can I move in a turn? Most set this to 6, some set it to 7, or 5, or any other number that you pick. A unit has an assigned damage formula. Again, most use Y, some use Z. Or if you want to introduce Q and J, you can add the formulas as new options and just pick from those (think enumerations here). Hell, if you do it right, all of them use formula K and just provide different coefficients and constants.

A rule of thumb I would suggest regarding component systems: if the vast majority of your component implementations involve less than 10 lines of unique code that is specialized for that component type, you're doing it wrong.

There's nothing bad about simple components, mind you; but most of them are going to be fairly rich, not trivial.

For your case, movement speed is trivial. Damage formula is trivial. In the OP's case, basically everything that would have been a component is really just a function.

Put another way: start your organization by grouping lines of code into routines. Group routines into modules (classes, namespaces, packages, whatever your language of choice considers a cohesive unit). Group the use of modules into components. Group components into entities. Group entities into worlds.

If at any point you don't have enough stuff to make a group (i.e. fewer than 3 of something), stop building additional layers of organizational abstraction.

Share this post

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

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By Alexander_Vovk
      Hello Guys!
      Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
      Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
      Thank you
      Best Regards
      Alex Vovk
      Co-Founder of Sixteen Squares
    • By RoKabium Games
      Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!
    • By JoshuaFraser
      Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }  
    • By Erik Nivala
      So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
      Is there a "standard" way that this is usually done that i am missing?
      I am fairly new to programming so any help is appreciated!
    • By MintyLyton
      I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website. 
    • By ethancodes
      I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
      Here is the code for the pick up manager:
      // Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
      public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }  
      There is also a Base Pick Up:
      public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed. 
    • By D34DPOOL
      Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
      Posted by D34DPOOL on May 20th, 2018
      Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
      What is required:
      Skill using C#
      Experience with Unity
      Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
      Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
      It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!
      To apply email me at mangemason@yahoo.com
    • By davejones
      Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

      Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
    • By MoreLion
      hey all! We are looking for members for our Unity horror game! 
      Here’s the story:
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
      This game is not a long development game, I have loads other game ideas,
      I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
      And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
      There is some concept art one of our concept artists have made
      If interested email liondude12@gmail.com
    • By Canadian Map Makers
      GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

      Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.


      We would like programmers and graphical artists to come onboard to (initially) create:

      A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
      A module where city infrastructure can be built on a real 3D interactive landscape.
      For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.


      More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).


      This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.


      Best regards,

      Steve Chapman (Canadian Map Makers)

  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
    • Total Posts

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!