Should my game's entities use global variables?Allocating Entities within an Entity SystemLua ImplementationHow can I correctly use an unordered_multimap as entity and component storage?Create entity from template in component-based engineAdding new components and systems in my ECS requires lots of boilerplate codeUpdating a multithreaded Entity-Component-SystemHow can I defer the initialization of my level's entities until I need them?Polymorphism vs cache-friendlinessGame engine tool generating game entitiesIs it possible to avoid global data in a Multi User Dungeon (MUD)?

Why should I always enable compiler warnings?

Is there a "right" way to interpret a novel? If so, how do we make sure our novel is interpreted correctly?

For how long could UK opposition parties prevent new elections?

2.5 year old daughter refuses to take medicine

Does the wording of the Wrathful Smite spell imply that there are other living beings that aren't considered "creatures"?

Is it appropriate for a professor to require students to sign a non-disclosure agreement before being taught?

Are there any space probes or landers which regained communication after being lost?

Number of aircraft to operate in an airline company

Usage of Offrir and Donner

Does the word “uzi” need to be capitalized?

How would two worlds first establish an exchange rate between their currencies

Might have gotten a coworker sick, should I address this?

Should my game's entities use global variables?

How to split a string by the third .(dot) delimiter

Can I say "I will encrypt something" if I hash something?

What was the first LISP compiler?

Does the mana ability restriction of Pithing Needle refer to the cost or the effect of an activated ability?

What is the origin of the term describing a game as a ‘Heartbreaker’?

I changed a word from a source, how do I cite it correctly?

What does my colleagues' question really mean?

Georgian capital letter “Ⴒ” (“tar”) in pdfLaTeX

SQL Server table with 4,000,000 rows is 40GB

Why is there a が in 深淵に臨むが如し?

Can I use ratchet straps to lift a dolly into a truck bed?



Should my game's entities use global variables?


Allocating Entities within an Entity SystemLua ImplementationHow can I correctly use an unordered_multimap as entity and component storage?Create entity from template in component-based engineAdding new components and systems in my ECS requires lots of boilerplate codeUpdating a multithreaded Entity-Component-SystemHow can I defer the initialization of my level's entities until I need them?Polymorphism vs cache-friendlinessGame engine tool generating game entitiesIs it possible to avoid global data in a Multi User Dungeon (MUD)?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


I have a base class called Entity and several sub classes like Player and Goblin. They all have the method update(delta), but that's not enough to update Goblin for example, which also requires setTargetPosition(vec2) to get updated properly.



All sub classes are stored together in a single vector vector<Entity*> entities.



Solution 1 is to use some C++ version of JavaScript's instanceof and depending on class call methods like update() and setTargetPosition().



Solution 2 is to have a source file with global variables like Goblin's target position and thus only update() is necessary because all the data that's needed is in the file with global variables.



Please give me a better solution than those above. Thanks.










share|improve this question







New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 2




    $begingroup$
    Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
    $endgroup$
    – Alexandre Vaillancourt
    12 hours ago

















1












$begingroup$


I have a base class called Entity and several sub classes like Player and Goblin. They all have the method update(delta), but that's not enough to update Goblin for example, which also requires setTargetPosition(vec2) to get updated properly.



All sub classes are stored together in a single vector vector<Entity*> entities.



Solution 1 is to use some C++ version of JavaScript's instanceof and depending on class call methods like update() and setTargetPosition().



Solution 2 is to have a source file with global variables like Goblin's target position and thus only update() is necessary because all the data that's needed is in the file with global variables.



Please give me a better solution than those above. Thanks.










share|improve this question







New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 2




    $begingroup$
    Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
    $endgroup$
    – Alexandre Vaillancourt
    12 hours ago













1












1








1


1



$begingroup$


I have a base class called Entity and several sub classes like Player and Goblin. They all have the method update(delta), but that's not enough to update Goblin for example, which also requires setTargetPosition(vec2) to get updated properly.



All sub classes are stored together in a single vector vector<Entity*> entities.



Solution 1 is to use some C++ version of JavaScript's instanceof and depending on class call methods like update() and setTargetPosition().



Solution 2 is to have a source file with global variables like Goblin's target position and thus only update() is necessary because all the data that's needed is in the file with global variables.



Please give me a better solution than those above. Thanks.










share|improve this question







New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I have a base class called Entity and several sub classes like Player and Goblin. They all have the method update(delta), but that's not enough to update Goblin for example, which also requires setTargetPosition(vec2) to get updated properly.



All sub classes are stored together in a single vector vector<Entity*> entities.



Solution 1 is to use some C++ version of JavaScript's instanceof and depending on class call methods like update() and setTargetPosition().



Solution 2 is to have a source file with global variables like Goblin's target position and thus only update() is necessary because all the data that's needed is in the file with global variables.



Please give me a better solution than those above. Thanks.







c++






share|improve this question







New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question







New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question






New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 12 hours ago









ComludComlud

83 bronze badges




83 bronze badges




New contributor



Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




Comlud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 2




    $begingroup$
    Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
    $endgroup$
    – Alexandre Vaillancourt
    12 hours ago












  • 2




    $begingroup$
    Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
    $endgroup$
    – Alexandre Vaillancourt
    12 hours ago







2




2




$begingroup$
Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
$endgroup$
– Alexandre Vaillancourt
12 hours ago




$begingroup$
Who calls setTargetPosition? If they know it's a goblin, why would they need to dynamic_cast them?
$endgroup$
– Alexandre Vaillancourt
12 hours ago










2 Answers
2






active

oldest

votes


















3














$begingroup$

Your design is at odds with reality, and you need to bring the two into alignment.



The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just update() that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.



Your interface for Entity is not rich enough to actually express reality: some Entity implementations require extra information to fully update themselves, information that is not present in Entity. You can address this in a few ways.



One way is to give Entity that information; this means storing the target position or target entity in Entity itself instead of Goblin, which now let's Entity have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.



What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate std::vector<Goblin*> so you know everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both update() them and set their target positions all in a loop.



This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.



This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.



And of course it doesn't involve dynamic_cast or the stashing of information in well-known globals, as requested.






share|improve this answer











$endgroup$














  • $begingroup$
    Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
    $endgroup$
    – Alexandre Vaillancourt
    11 hours ago










  • $begingroup$
    Probably, this kind of problem is a favorite of mine.
    $endgroup$
    – Josh
    11 hours ago










  • $begingroup$
    Thank you Josh for the great answer!
    $endgroup$
    – Comlud
    53 mins ago


















2














$begingroup$

Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory



It appears you're designing a game from scratch. Let me first say, no, you should not use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.



In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.



Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data now as it may get quite cluttered quite fast.



Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.



For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.






share|improve this answer










New contributor



Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





$endgroup$

















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "53"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );







    Comlud is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f175359%2fshould-my-games-entities-use-global-variables%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    $begingroup$

    Your design is at odds with reality, and you need to bring the two into alignment.



    The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just update() that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.



    Your interface for Entity is not rich enough to actually express reality: some Entity implementations require extra information to fully update themselves, information that is not present in Entity. You can address this in a few ways.



    One way is to give Entity that information; this means storing the target position or target entity in Entity itself instead of Goblin, which now let's Entity have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.



    What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate std::vector<Goblin*> so you know everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both update() them and set their target positions all in a loop.



    This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.



    This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.



    And of course it doesn't involve dynamic_cast or the stashing of information in well-known globals, as requested.






    share|improve this answer











    $endgroup$














    • $begingroup$
      Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
      $endgroup$
      – Alexandre Vaillancourt
      11 hours ago










    • $begingroup$
      Probably, this kind of problem is a favorite of mine.
      $endgroup$
      – Josh
      11 hours ago










    • $begingroup$
      Thank you Josh for the great answer!
      $endgroup$
      – Comlud
      53 mins ago















    3














    $begingroup$

    Your design is at odds with reality, and you need to bring the two into alignment.



    The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just update() that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.



    Your interface for Entity is not rich enough to actually express reality: some Entity implementations require extra information to fully update themselves, information that is not present in Entity. You can address this in a few ways.



    One way is to give Entity that information; this means storing the target position or target entity in Entity itself instead of Goblin, which now let's Entity have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.



    What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate std::vector<Goblin*> so you know everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both update() them and set their target positions all in a loop.



    This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.



    This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.



    And of course it doesn't involve dynamic_cast or the stashing of information in well-known globals, as requested.






    share|improve this answer











    $endgroup$














    • $begingroup$
      Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
      $endgroup$
      – Alexandre Vaillancourt
      11 hours ago










    • $begingroup$
      Probably, this kind of problem is a favorite of mine.
      $endgroup$
      – Josh
      11 hours ago










    • $begingroup$
      Thank you Josh for the great answer!
      $endgroup$
      – Comlud
      53 mins ago













    3














    3










    3







    $begingroup$

    Your design is at odds with reality, and you need to bring the two into alignment.



    The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just update() that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.



    Your interface for Entity is not rich enough to actually express reality: some Entity implementations require extra information to fully update themselves, information that is not present in Entity. You can address this in a few ways.



    One way is to give Entity that information; this means storing the target position or target entity in Entity itself instead of Goblin, which now let's Entity have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.



    What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate std::vector<Goblin*> so you know everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both update() them and set their target positions all in a loop.



    This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.



    This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.



    And of course it doesn't involve dynamic_cast or the stashing of information in well-known globals, as requested.






    share|improve this answer











    $endgroup$



    Your design is at odds with reality, and you need to bring the two into alignment.



    The thesis of your design seems to be, essentially, that "everything is an entity" and "everything is in one big list" because you can just update() that whole list. That's fine, up until the point where it isn't, which is the point you've reached now.



    Your interface for Entity is not rich enough to actually express reality: some Entity implementations require extra information to fully update themselves, information that is not present in Entity. You can address this in a few ways.



    One way is to give Entity that information; this means storing the target position or target entity in Entity itself instead of Goblin, which now let's Entity have the requisite interface to manage and update the target position. If most subclasses won't use this information, however, this is somewhat wasteful.



    What I'd argue is the better way is to simply treat the entities that need special handling (goblins) differently. Store them in a separate std::vector<Goblin*> so you know everything in that vector is a goblin and can use the goblin-specific APIs. Then you can both update() them and set their target positions all in a loop.



    This avoids complicating the base class with data and methods that aren't universal to all child types. It also gives you a much stronger locality of reference with respect to the update of the goblin instances: you can know when all the goblins start and stop the update work because there's an explicit loop for it, rather than a loop over the big entity "master list" that is potentially processing entity types in an effectively-random order.



    This can be a huge win when when you end up having other logic that really wants to depend on the goblin update being "done," as well as for finding places where your work can be data-parallel and benefit from concurrency.



    And of course it doesn't involve dynamic_cast or the stashing of information in well-known globals, as requested.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 11 hours ago

























    answered 11 hours ago









    JoshJosh

    94.5k17 gold badges212 silver badges330 bronze badges




    94.5k17 gold badges212 silver badges330 bronze badges














    • $begingroup$
      Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
      $endgroup$
      – Alexandre Vaillancourt
      11 hours ago










    • $begingroup$
      Probably, this kind of problem is a favorite of mine.
      $endgroup$
      – Josh
      11 hours ago










    • $begingroup$
      Thank you Josh for the great answer!
      $endgroup$
      – Comlud
      53 mins ago
















    • $begingroup$
      Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
      $endgroup$
      – Alexandre Vaillancourt
      11 hours ago










    • $begingroup$
      Probably, this kind of problem is a favorite of mine.
      $endgroup$
      – Josh
      11 hours ago










    • $begingroup$
      Thank you Josh for the great answer!
      $endgroup$
      – Comlud
      53 mins ago















    $begingroup$
    Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
    $endgroup$
    – Alexandre Vaillancourt
    11 hours ago




    $begingroup$
    Did you write an answer about a similar topic not long ago? I tried to find it but I couldn't.
    $endgroup$
    – Alexandre Vaillancourt
    11 hours ago












    $begingroup$
    Probably, this kind of problem is a favorite of mine.
    $endgroup$
    – Josh
    11 hours ago




    $begingroup$
    Probably, this kind of problem is a favorite of mine.
    $endgroup$
    – Josh
    11 hours ago












    $begingroup$
    Thank you Josh for the great answer!
    $endgroup$
    – Comlud
    53 mins ago




    $begingroup$
    Thank you Josh for the great answer!
    $endgroup$
    – Comlud
    53 mins ago













    2














    $begingroup$

    Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory



    It appears you're designing a game from scratch. Let me first say, no, you should not use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.



    In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.



    Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data now as it may get quite cluttered quite fast.



    Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.



    For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.






    share|improve this answer










    New contributor



    Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $endgroup$



















      2














      $begingroup$

      Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory



      It appears you're designing a game from scratch. Let me first say, no, you should not use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.



      In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.



      Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data now as it may get quite cluttered quite fast.



      Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.



      For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.






      share|improve this answer










      New contributor



      Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      $endgroup$

















        2














        2










        2







        $begingroup$

        Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory



        It appears you're designing a game from scratch. Let me first say, no, you should not use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.



        In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.



        Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data now as it may get quite cluttered quite fast.



        Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.



        For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.






        share|improve this answer










        New contributor



        Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        $endgroup$



        Preface: I've designed several game engines in C and C++ by hand and have plenty of experience with game engine architectural patterns and theory



        It appears you're designing a game from scratch. Let me first say, no, you should not use global variables for this purpose. They are stored in what's called the BSS or Data segment and while you may not notice the performance hit from cache misses right away, I can guarantee that once you have your game in a more developed state, you will be kicking yourself in the butt for not outlining the design of your custom engine before embarking on the design journey.



        In simple terms, a cache miss happens when a program tries to accesses memory which is "far away" from the memory being frequently or currently accessed, which in a game is primarily going to be stack memory. A professor once told me "Cache is king" when it comes to performance.



        Aside from that, you may want to read through a common architectural pattern called Entity-Component-System architecture which is easy to understand and simple to implement. Since, in a custom engine, you will have a graphics implementation, a serializing implementation for saving loading, potentially a reflection system, audio or the like, your program will be moving through different segments of memory quite often and it is important to begin compartmentalizing your data now as it may get quite cluttered quite fast.



        Like all tools in the game-dev toolbox, global variables have their time and place. They can be quite useful in reflection with regards to entity-factories when using static initializers, or for singleton classes. However, for storing the objects which make up the "meat-and-potatoes" of your game, you should certainly plan on a different strategy other than global variables.



        For more complete information regarding memory management, this is an excellent overview of pitfalls and strategies and may provide a more complete picture to help you plan.







        share|improve this answer










        New contributor



        Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        share|improve this answer



        share|improve this answer








        edited 1 hour ago





















        New contributor



        Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        answered 2 hours ago









        Jon KoelzerJon Koelzer

        313 bronze badges




        313 bronze badges




        New contributor



        Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




        New contributor




        Jon Koelzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.


























            Comlud is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded

















            Comlud is a new contributor. Be nice, and check out our Code of Conduct.












            Comlud is a new contributor. Be nice, and check out our Code of Conduct.











            Comlud is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Game Development Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f175359%2fshould-my-games-entities-use-global-variables%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її