Weekly Update – August 26, 2022

After literally years of research, brainstorming, analysis, and procrastination, the types of resources consumed by abilities have been determined. This decision has been drawn out by many dependent questions regarding Legend’s underlying resource management design: are resources finite or infinite? Is there a hunger clock? Do health, magic, etc. regenerate? Not all of the questions have been answered. I aspired to find the perfect solution, but the model is too complex to assemble, and I no longer believe a perfect solution exists anyway. I increasingly aim for solutions that are good enough, solutions that don’t offer complete flexibility, but are flexible enough. I embrace the resulting constraints, for they shrink the answer space, and foster creativity. And thus, at the end of the ability resource design journey, I arrived not at revelation but convention, with the health/stamina/magic trinity, a staple of the PC RPG.

  • Ability resource consumption design. Abilities may consume stamina, magic, health, and/or items. Magic fuels spells, stamina powers physical feats, and items are needed for specific skills such as picking locks. Like health, stamina and magic are represented in points. The quantities of resources consumed by each ability will be fine-tuned during balancing.
  • Player magic and stamina meters. Stamina and magic meters now join the Health meter. I reduced the dimensions of the meters so that they cover up a smaller screen area.
Redesigned health/stamina/magic meters
  • New Action Step: Consume Resources. Luckily, I didn’t have to implement a new system to handle resource consumption; it fits nicely into the Action Step framework, becoming another building block for constructing actions. This was the most logical solution, since abilities essentially just invoke actions.    
  • Added Action Source to Actions. Actions are defined using the following structure: [Actor] do [Action Type] with [Item(s)] on [Target] in [Context]. For the Consume Resources Action Step to work, it needs the source of the action (the ability that invoked the action), so that it knows which resources, and how much of each resource, to consume. The action source has been added to the actor structure, making the structure now: [Actor] do [Action Type] from [Source] with [Items] on [Target] in [Context]. This required a lot of changes in the code, but was done quickly using global search and replace (which is surely an architecture smell).
  • New items
    • Magic and Stamina Potions. Self explanatory.
  • New abilities
    • Health to Magic. Recover magic at the cost of health. No class with healing abilities will be able to use this, since it would be possible to have unlimited health and magic.
    • Magic to Stamina. Recover stamina at the cost of magic.
  • Visual effects. While looking for a way to modify sprite colors at runtime (I need to display grayscale versions of sprites and make sprites appear frozen when they are hit with an Ice spell), I came across a Unity Asset, All in 1 Sprite Shader. It does far more than I need (at least currently), but it was very popular and highly rated (and on sale) so I bought it. Of all the Unity assets I’ve installed, this asset is probably the easiest to learn; simply add the component to a gameobject and, using the component’s UI, select the visual effects you want to apply. However, I don’t think I’m using it in the intended way. I didn’t want to add the component to the dozens of actor and item prefabs because I didn’t want the visual effect to be always on, and I didn’t want to maintain an extra component for actors and items. So, I just used it to make materials, and I’m applying the effects at runtime by changing the sprite material.
  • Improved random Map Element selection. Previously, all Map Elements were assigned a rarity level, which served as the weight in a weighted randomizer. The problem with this is that the rarity distribution changes depending on the number of Map Elements of each rarity level. I’ve now split the selection into two steps. The first step selects the rarity level using a fixed set of probabilities. The second step selects a Map Element from the list of Map Elements of the selected rarity level. This ensures that Map Elements are correctly chosen based on the rarity distribution.
  • Bug fixes
    • Quick Switch and Hotbar slots still interactive after the player dies
    • The action indicator cursor still appears after the player dies
    • Enemies stop moving when the player moves out of sight
  • Minor improvements
    • The Escape key now cancels the Select Cell prompt. My goal is for the game to be completely playable using a keyboard and/or mouse.
    • Ability resource consumption support
      • Preventing abilities from being used if there are insufficient resources
      • Dimming slots containing abilities that can’t be used due to lack of resources
      • Tooltips indicate why ability slots are dimmed

Next week, the major task is reassigning sound effects. I’ve purchased several collections from the Unity asset store, but I recently pulled the files out of the Unity project because they were making project snapshots huge. Now, I need to bring only the sound effects that the game is using back into the project. Beyond that, there will be more play-testing and tightening things up. 

Weekly Update – June 3, 2022

In my relentless pursuit of increasing software development productivity, I started the week off pondering what is slowing me down the most. I kept coming back to aspects of object-oriented programming – encapsulation, abstraction, inheritance/composition, polymorphism. OOP has always been a double-edged sword for me, providing both solutions and problems. Certainly some of my issues are the result of my shortcomings as a developer, but I believe there are inherent shortcomings in OOP as well. A frequent challenge is determining where things belong, and a frequent source of bugs is putting things in the wrong place. I began questioning whether data and functionality belonged together in the same class (I was quite deep into the rabbit hole at this point) and if I could reduce complexity by separating the two. I also considered making data and functionality, once separated, completely public (I know, OOP heresy) and using either immutable or versioned data. I googled these ideas to see what already existed and found something very close: Data-Oriented Programming (DOP). Now, it would be impractical to go back and rewrite 2+ years of code using a DOP paradigm. But, I’m going to experiment with it for some of the new code I’m writing (see the AI example below). 

  • AI Overhaul part 2. I thought I was done with AI rework after last week, but I put even more time into it this week. To make the new composition-based AI configurable in the Unity editor, I added AIType classes (implementing the Type Object pattern). inheriting from ScriptableObject, I also made the pluggable components of AIType, such as the observation and action deciders, ScriptableObjects. The legacy AI classes were gutted and consolidated. AI state data was moved into a separate generic data structure (see below) and AI functionality was moved into the AIType classes. I added general AI behaviors such as offense and flee, and mapped actions to the behaviors. This simplifies the action decider code because only the behavior has to be specified; the behavior class will return all of the applicable actions to the action decider. With these improvements, I can assemble AI’s in the Unity editor, provided that the pluggable components have been written. I may need to move to data-driven behavior trees if the AI logic becomes too complicated, but for now I’ll stick with conditional statements.
  • Generic Data Structure. To support my data-oriented programming experiment, I created a class to act as a general-purpose data container. It’s essentially a map data structure, but contains three dictionaries to store values of different types (bools, ints, and objects). It’s not sophisticated but it works. I’m now using this to store AI state data, which varies by AI type. The syntax for accessing data within the structure is more cumbersome than individually defined variables, but that drawback is outweighed by flexibility and ease of serialization/deserialization. I also like that the syntax makes it obvious which variables are part of the state.

Next week’s goals are the same as last week’s goals: add the vampire and 1-2 more enemies to test the new AI, and add a few new abilities.

2021 Year in Review

2021 Retrospective

Legend has been in development for 2.3 years. It’s hard to believe that that much time has passed since I started working on the game. I don’t know if anyone else has experienced this, but how I felt at the two-year mark was in stark contrast to my feelings at the one-year mark. After the first year of development, I was thrilled with how much I had accomplished and excited for the future. At two years, panic set in. How could I possibly finish at the rate I was going? Was I wasting my time? Was this game even any good? 

Ultimately, the mid-gamedev crisis was a good thing. This was my brain telling me to reassess and correct course. That’s exactly what I did in the latter part of the year. The reality was that, at the rate Legend was progressing, it would need at least several more years to release. I don’t want to wait that long (I have more games to do!). I cut a large chunk of planned features while preserving the original vision. I forced myself to make decisions. I have a tendency to postpone decisions as long as possible to avoid limiting possibilities. It’s been a sure-fire way of keeping completion in the distant future.

Development thus far has consisted primarily of building the game system framework, and rebuilding many facets of the framework as my Unity knowledge increased and my ideas crystalized. Heading into 2022, the framework is done and development shifts to using the framework to flesh out the actual game.

What I said I was going to do in 2021:

Replacing the stock art

Completion: 0%

I’m still using Oryx. I still have some uncertainty about the exact 2D perspective that will be used. I also feel that the art doesn’t need to be replaced until the game is ready for a public release.

More content 

Completion: 5%

A handful of new enemies, items, and objects were added. Every piece of existing content was reworked in some way, for example extracting a parent class for actors and items, and moving from room-based to element-based map generation.

More polish

Completion: 30%

At the beginning of 2021, I never would have expected to accomplish as much as I did in this area. I considered polish something you do at the end of development. That largely is the case, but I’m using “polish” loosely here to refer to any visual and audio effects beyond the bare minimum, and refinement of any sort, such as fine tuning procedural generation and balancing combat. The game looked bad and felt dull whenever I did testing. Even though I knew I’d improve the look and feel before launch, I was still getting discouraged. For my own psychological benefit more than anything else, I added some game juice, including:

  • Particle effects
  • Better combat and movement animations 
  • Screen shake
  • Environmental impact: corpses, particle effect residue
  • Sound effects

Visuals | Sound Effects

This did the trick; I could finally envision other people playing the game.

Community building

Completion: 5%

I posted a weekly dev update on the website and Sharing Saturday on r/roguelikedev. I posted the link to each Sharing Saturday update on Twitter. I occasionally posted videos on Youtube. I have tiny followings on those channels. I continued to spend a minimal amount of time on community in favor of game development.

Early access release (aspirational goal)

Completion: 10%

This was nowhere close to happening, but there was movement toward this goal due to focusing on it at the end of the year. I also created a mind map visualizing features by release and a roadmap.

What else happened in 2021:

The new map generator, started in 2020, was finished in January. I built some dev tools for procedural generation analysis, tuning, and troubleshooting: an interactive map generation visualizer and a map graph visualizer. These proved to be very handy.

A map graph

I made another major change to map generation later in the year with the addition of Map Elements. These are the basic building blocks for populating a map with content after the map structure’s been created. They’re hierarchical and modular, enabling rooms to be constructed from layers of interchangeable components and reuse common components. For example, many room types can include an Abandoned Map Element that adds cobwebs and debris to give the appearance that the room is abandoned.

Maps became both more varied and more playable. Map configuration parameters, which dictate a map’s structure (number of rooms, room sizes, room distances, room themes, etc.) are now randomized. This additional layer of procedural generation increased the variety of maps while maintaining consistency within a map. Map configuration parameter ranges were fine-tuned to avoid problematic maps. Room type probability changed from a linear distribution to a weighted distribution based on rarity to give maps a more logical composition of rooms.

Significant UI work was done. New screens were added, a hotbar was added, and the main game UI was refined. 

Class selection screen
Inventory and hotbar

In action:

AI was expanded. Now, actors can have their own AI controllers and behave differently than other actors. AI controllers can be reused across multiple actor types. Actors can now track any number of other actors, enabling them to do much more than charging the player. They can attack, defend, and interact in other ways with tracked actors as dictated by their AI controller. Actors now gain awareness of events based on their vision and hearing ranges and act based on the type of event occurring. Each actor has its own inventory and the ability to pick up items and use them. When an actor dies, other actors can acquire the items it was carrying.

In light of my time constraints and the mountain of work remaining, I made a deliberate effort throughout the year to increase my productivity. The ways in which I did this include:

  • Reducing and simplifying code.
  • Moving logic from code to configuration (physical material interactions, game events).
  • Adding unit testing.
  • Adding an in-game console for spawning objects to accelerate playtesting. 
  • Adding more granular logging so that I have more information to troubleshoot.
  • Consolidating test settings into a single design-time editable object.
  • Switching my IDE from Visual Studio to Rider.
  • Reorganizing my Unity editor layout.
Reorganized Unity Editor layout

Finally, code rework occurred throughout the year. Most of it was necessary to keep the code maintainable, but I also know that I am overly eager to rework code and sometimes create more problems for myself than I solve. As the year progressed, the rework did slow down. There are two reasons for this: 1) the framework reached maturity and 2) I became more selective with when I reworked code. Before I make changes or add new features, I now consider what compromises I can make and what I can do within the existing framework to avoid rework. 

2022 Outlook

This year’s goals are essentially the same as last year’s. However, the priorities have changed. An early access release is now the primary goal. Original art, a requirement for the release, is also a top priority. Effort will be concentrated on what is absolutely necessary for public release, including tightening the game loop, balancing, and clearing the bug list. 

Weekly Update – December 31, 2021

It was a great finish to the year. The main gameplay loop is coming together, levels are more balanced, changes have gotten easier.

  • Dungeon level-based equipment drops. Each dungeon level now contains equipment appropriate to the player’s power curve. Prior to this change, dropped equipment was random. A player on level one could find the best armor in the game, and a player on level twenty could find a copy of the short sword that they started with. Now the player will typically get equipment on the power curve, occasionally equipment one tier above or below the curve, and rarely equipment two tiers above the curve.
  • Map element placement overhaul. Previously, map elements were added by calculating the number of elements to place based on the number of map nodes and then randomly selecting a node and an element for each iteration. This was quick to implement but it unevenly populated the map with elements. I changed this to iterating over each map node to guarantee that it received one and only one map element. Additionally, I moved enemy placement responsibility from the map generator to the map elements themselves because the available enemies varies based on the map element. I also added a way to control the relative frequency of map elements, so that some occur more or less often that others.
  • Map element hierarchy. After creating many map elements it became evident that there’s a natural hierarchy – some elements define an entire map node while other elements perform a subordinate function such as decoration. I organized the folder structure and added inheritance into the classes. This also helped identify which map elements should be used directly by the map generator and which ones should be used by parent map elements.
  • Most destructible objects are now destroyed with one hit. Walking into a room full of barrels and crates and having to hit each one a few times to destroy it was realistic but tedious. I made these and similar objects destructible in one hit. Some objects that are not routinely destroyed and should require some effort, such as wooden doors, still take multiple hits.
  • Combat modifiers for standing on corpses. Standing on a corpse now causes a slight combat disadvantage, the thinking being that an actor can’t maneuver as well. More importantly, it adds another tactical option for combat.
  • Enabled Unity’s Universal Render Pipeline. I honestly didn’t know about this (embarrassed to say that with two years of Unity experience under my belt now) and stumbled upon it while researching lighting in Unity. To use some of the lighting features, the URP was required. It wasn’t too difficult to enable. I had some issues with materials in a couple of third party assets. I’m still fuzzy on the URP but it seems like the right choice given that I have an aspirational goal of releasing on multiple platforms and the game is 2D. Ironically, I ended up using a lighting asset from the Unity Asset Store rather than the built-in lighting because the latter didn’t have all the functionality I needed.
  • Added lighting, then removed it (temporarily). I set up basic lighting (darkened dungeon, player visibility, torch light) using Unity out-of-the-box lighting and it looked pretty good, but I ran into some limitations. I bought a Unity asset, Smart Lighting 2D, to get more functionality. I got it partially working, but I’m still learning how to use it. I had to put it on hold because I had some more important things to do this week. I’ll pick it back up in January.
  • Fixed some bugs that had been hiding for a long time. I discovered a few bugs that causing problems I didn’t even know the game had! For example, one of the methods for fetching cells in a pattern was returning all of the cells in a map node rather than the room inside the map node. This explained the occasional mysterious placement of objects outside of a room. I also realized that enemy AI was executing some of the code for handling player clicks. This was ultimately benign, but still totally wrong so I corrected it.
  • Increased the frequency of enemies and items for the standard room. Most rooms use a generic map element that sometimes adds enemies and items. Sometimes wasn’t enough; there were too many empty rooms, and maps often felt dull. Simply by increasing the frequency of enemies and random items, the game was funner to play. 

Next week, I’m making some more minor tweaks to gameplay and map generation with the end goal of making level one challenging and fun. 

Weekly Update – December 24, 2021

Happy Holidays everyone! With a few days off from work this week, I got a lot done! Many of the changes were visual, which always feels more productive. I primarily worked on combat game juice.

Combat game juice
  • Corpses. Slain enemies now leave corpses behind. This increases the player’s impact on the environment and will be used for a variety of mechanics including reanimating corpses, enemies reacting to corpses, and combat modifiers when fighting on a cell containing a corpse. I was pleasantly surprised to find that this feature didn’t require any code changes. It was implemented entirely in the Unity Editor using the custom trigger/effect framework developed earlier in this year.
  • Particle effect residue. Particle effects can now leave permanent residue, such as blood stains and bone fragments. Along with corpses, this is intended to increase the player’s feeling of leaving a mark on the environment. You can very clearly tell where battles took place and the size of those battles.
  • New walk and attack animations. After getting frustrated a couple of weeks ago by not being able to make a decent walk animation, I took some time to learn more about classic animation techniques. I applied the squash and stretch technique to walk and attack animations. I also added a slight pause to the beginning of attacks for anticipation. I got much better results this time around, due primarily to a more precise application of squash and stretch.
  • Replaced animation implementation. In researching Unity animation techniques I discovered Unity’s new 2D Animation package. This package provides a way to reuse animations with different sprites. Previously, I was using what I believe is the traditional methodology – for each animated game object prefab, create an animation override controller for the animation state machine, duplicate the animations referenced in the animation controller, and replace the sprites in the animations. This technique has major drawbacks: 1) it’s tedious 2) it generates a lot of redundancy. If I ever needed to change a common animation such as walking, I’d have to change every copy of the animation. The 2D Animation package provides a way to define an animation only once and swap out sprites based on the game object using the animation. This is done by adding a sprite library and sprite resolver component to each animated actor and configuring animations to reference the spriter renderer properties rather than the sprite directly.
  • Added a parent to all animated actor prefabs. This was suggested by /u/Notnasiul as a way to use relative positioning in animations and as a general good practice. It took around an hour to go through the existing actor prefabs, add a parent game object, and move the Sprite Renderer component to a child game object. And… it worked great!
  • Directional attack animations. With the capability to control relative game object position in the Unity animator, and trigger events in animations, I was able to remove the code that was previously responsible for this. This code was complicated. It updated the game object position on each Update() based on an easing function and managed time-based state changes for different points in the animation where events had to occur. I was glad to see it go.
  • Reconfigured my Unity Editor layout. Up until now I’ve been using the default Unity layout. This layout has been workable but not optimal. The project asset hierarchy panel isn’t large enough, the game object hierarchy panel is too large, and some tabs that need to be viewed concurrently (such as Animation and Scene) are by default in the same panel. I reorganized the panels to better suit the needs of this project. This is the end result.

Next week’s goal is to give level 1 the right amount of challenge. To do this, I’m going to tweak stats and drop frequencies for items and enemies. I want to finish the year with at least one good level. 🙂

Weekly Update – December 17, 2021

Minor progress this week. I have some time off from work over the next two weeks and look forward to getting more done.

  • Added screen shake on hits. Continuing down the game juice road, every combat hit results in a screen shake now. I think it looks good, but wonder if some people may find it excessive or unnecessary. In line with the “sword and sorcery” theme, I want combat to feel exciting, and somewhat over the top. I’ll leave it in, but may dial down the effect. As with the blood particle effects, I want to vary the magnitude according to the amount of damage done. 
  • Distinguished missed hits from zero-damage hits. Whether the attacker hits or misses is based on the attacker’s chance to hit and the defender’s chance to evade. When a miss occurs, the text “Missed” appears instead of a damage amount. The damage from a successful hit is based on the attacker’s attack damage and the defense’s damage absorption. The amount of damage done is displayed when a successful hit is performed. A zero-damage hit occurs when the defender fully absorbs the hit. Previously, a zero-damage hit was being displayed as a miss, simply because this was easier to code. But, this didn’t accurately reflect what was happening. I needed to distinguish misses and zero-damage hits to play the correct sound effect (a whoosh vs a weapon hitting armor), whether to display damage and blood particle effects, and to degrade the attacker’s weapon and defender’s armor. I also wanted to communicate to the player whether no damage was being taken because of evasion or damage absorption.
  • Moved player gold count back to the main screen. The player’s gold count was initially displayed on the main screen. I moved it to the inventory screen at some point to simplify the main screen UI. However, acquiring gold is so closely tied to the gameplay and the theme (treasure is a primary motivation for exploring the dungeon) that I moved the count back to the main screen.
  • Researching Unity animation with relative positions. I want to make combat animations more complex. To do that, I want to move combat animations out of code and into Unity animations so that I can leverage existing engine/editor functionality. There doesn’t seem to be a straightforward way to move a game object relative to its current position in a Unity animation. A common recommendation is to create a parent object so that the child can move relative to the parent. It’s not an ideal solution, but it’s the best one I’ve found.

Next week, I’ll continue adding game juice to combat. This will likely be the focus for the remainder of December.

Weekly Update – July 16, 2021

Title Screen

One Release 3 feature completed this week: the Title Screen! It will likely completely change after I bring an artist onboard, but it gets the job done.

Title Screen

Finished Actor Refactoring

I dug myself into a deep hole last week by refactoring actors. Every unit test failed and there were a couple hundred compiler issues to fix. I’ve mostly climbed my way out of the hole since, and I think the actor architecture is solid enough now to get to the finish line. I now have:

  • Actors
    • The main actor class is a plain C# class for all actors. It contains all actor state and is therefore the only class involved in actor saving and loading.
  • Actor Types
    • A GameObject prefab is defined for each Actor Type. These prefabs are loaded into memory when the game starts. They use composition in a limited manner, typically having only Transform, SpriteRenderer, and Animator components. When a new actor is created, the corresponding Actor Type GameObject is instantiated and associated with the actor. 
    • A ScriptableObject prefab is defined for each actor type’s definition data. Composition is employed here as well, though it is not supported “out of the box” by Unity, at least not in the way I’m using it. The technique is to add a field to the ScriptableObject that is a parent class or interface, and create custom editors to enable an inherited class (or implementing class in the case of interfaces) to be selected from a dropdown. Reflection is used to get all of the subclasses and populate the dropdown. When an actor is created in the game, Activator.CreateInstance is used to instantiate the class. This allows me to define an actor’s AI and abilities, for example, in the editor instead of in code.

This isn’t an elegant solution, but it addresses the things that were bothering me about the previous architecture, namely redundant type data in each actor instance, having to use MonoBehaviours or ScriptableObjects for composition but not being able to easily save/load component state data, inadequate information hiding, circular dependencies, and unclear division of responsibilities between the different classes comprising actors. The drawbacks of this solution are having to maintain two prefabs for each actor type and not doing composition the “Unity way” with MonoBehaviours.

All Unit Tests Passing, More Unit Tests Added

I’m repeating myself from previous posts, but the unit tests have been well worth the investment in time.

Next week, the plan is to finish the class selection and load game screens. There are still some things that are broken from refactoring and I need to fix those too.

Weekly Update – July 9, 2021

Feeling a bit overwhelmed this week… I had to do some major rework (again) instead of working on new features. I find myself battling with Unity again, specifically where to put things – prefabs, components/MonoBehaviours, ScriptableObjects, plain vanilla classes. When I first started using Unity a couple of years ago, I tended to write code for everything, because that’s what I was familiar with. As I gained familiarity with Unity, I pushed myself to embrace it and fully leverage the editor capabilities. However, that produced a lot of constraints, and now I’m back to relying on code more (though not as much as in the beginning). Anyway, a lot happened this week due having a couple of days off:

  • Finished the save system. I mentioned last week on reddit that I was struggling to determine the best way to code the save system in Unity. I ended up pulling all state data out of MonoBehaviours and into plain classes for each object type. Nested objects are supported as well (serialized attributes have to be explicitly declared). All objects that need to be saved are nested in the Map class, so saving the game is as simple as serializing this class. Loading is a tad more complicated because, after deserialization, game objects have to be instantiated.
  • A byproduct of the save system was changing actors and items to inherit from the same base class. There’s a lot of commonality between actors and items – they’re in-game objects, they can be damaged, have status effects, etc. I was handling this through composition. Attributes were spread across multiple MonoBehaviours. Because Monobehaviours can’t be serialized, capture/restore state code needed to be written for each component. It made more sense to move all state attributes into a single serializable class. This was a case where inheritance made more sense than composition.
  • Another byproduct was pulling health into the base class from a MonoBehaviour. Previously, the Damageable component made an actor or item damageable. This component tracked health. However, each actor and item ended up needing this component so it didn’t need to be optional. Also, this was done to address the issue in the previous bullet. This change broke a lot more than I expected, but fortunately the unit tests helped pinpoint the issues quickly.
  • Test map generator. The map generator can now generate a map with designated layout, actors, and items. This will allow a greater degree of automated testing.
  • New map generation capabilities. Map generation now fully supports different sets of parameters. These parameter sets can be statically predefined in the Unity editor as ScriptableObjects, or dynamically generated in the initial steps of the map generator, enabling additional layers of procedural generation.

Next week, the goal is to finish the load game and select class screens, and start on the hotbar time permitting.

Weekly Update – July 2, 2021

Dev time was extremely limited this week. After reprioritizing Release 3 features, my plan for the week changed and I ended up working on the save system. This was functioning in Release 1 but I haven’t updated it for all the features and refactoring done in Release 2. So much has changed that I’m basically starting over. I’m also having to rework some classes that contain a mix of data that should be saved and data that shouldn’t or can’t be saved (e.g., MonoBehaviours). I read a lot of articles and watched a lot of videos on save systems in Unity. Most of what I found was aimed at beginners and only covered the basics. This video was helpful, but I didn’t like having to create a new temporary object and save and load methods with explicit setters and getters; it’s slow performance-wise and difficult to maintain. I’d rather just isolate the data that needs to be saved and serialize it. Either I haven’t discovered the right pattern, or saving complex data in Unity requires a lot of effort and there’s no way around it. I could put all of an object’s state data into a single plain C# class, but then I couldn’t use composition to build game objects. I could isolate the state data on each game object component, but then I’d have to individually serialize the data in each component, or aggregate the stage data spread across the components first. Ideally, the save system would simply save and restore game objects marked for saving and restoring. This is technically possible in Unity, but from what I’ve gathered it’s not advisable. Anyway, after some analysis paralysis, I started implementing the new save system starting with the map. Once a monolithic class, the map now simply contains its dimensions, a cell collection, and half a dozen other collections that are only used for procedural generation, such as the room collection. I don’t believe I need to save the procedural generation data after the map is created, so I’m not going to worry about saving that data for now (ideally, this data would be in a class specifically for map generation that is destroyed after the map is created; will refactor in the future). So, the bulk of the data being saved is the cell collection. Each cell contains multiple attributes, including value and reference types. By default, the serializer I’m using (Json.NET) serializes objects by value. This is a problem for “type” objects. For example, each cell has a cell type, such as a wall or a floor. Each cell type has many attributes. By default, Json.NET serializes all of the attributes in the cell type for each cell that has that cell type. This increases the size of the save file significantly and loses the reference to the original cell type object. I solved this problem by adding an attribute for the cell type’s unique id to the cell class. The advantages of this solution are 1) less data written to file and 2) when loading data, the reference to the cell type object can be restored by retrieving the cell type from a dictionary using the unique id as the key. I applied this pattern to other attributes as well, such as actor types and item types. As of now, the map successfully saves to file, but loading hasn’t been implemented.

Other than that, I briefly descended into a rabbit hole on story-driven procedural map generation. This came out of the map generation work I did last week on room types. I want maps to have some coherence or purpose rather than just being a random assortment of rooms, and cohesion across levels that is driven by an overarching procedurally generated story. Ideally, the player’s actions could alter the story and influence future levels. I created a conceptual framework for doing this and implemented some of the building blocks. However, after reprioritizing Release 3 features, this is on the backburner for now.

Next week, the goal is to get saving and loading working again and start on the hotbar.

Weekly Update – June 25, 2021

  • I stuck to the plan this week (for a change) and finalized the Release 3 features. I’ll publish a summary in next week’s post.
  • Added cell-based status effects. These are effects that are added when an actor moves onto a cell and removed when an actor leaves a cell. An example is a Darkness effect that limits the player’s visibility. This builds on the existing capability to add status effects by using an item or interacting with an object. This feature was unexpectedly difficult to add; a lot of the status effect code and Unity configuration needed to be reworked.
Darkness cell effect
  • Room features. Each room has a room type that determines what’s in the room. For example, a Shop Room contains a shop and a Treasure Room contains treasure. I needed to be able to apply different features to a room to do things like placing a trap inside of a treasure room. I added a base RoomFeature class and some child classes like ShopRoomFeature and TrapRoomFeature. This makes it possible to mix and match different features can create a wider variety of rooms than was possible using room types. I still need to fully incorporate this into the map generator, specifically by replacing the existing room generation with feature-based generation.
  • Overhauled effect triggering. I was never comfortable with the way I originally implemented the configuration of status effects caused by an object or item. Effects inherited from MonoBehaviour so that they could be added to game objects in the Unity editor. It worked, and it was designer-friendly, but it was unintuitive (it wasn’t obvious the purpose of the component was to cause an effect) and too heavyweight (multiple effects required multiple components). I converted effect types to ScriptableObjects and created a new class containing a list of effect types. I called this class TriggeredEffectCollection and used it to replace the individual effect components. Adding effects is now easier (add/remove from a list editor in the Unity inspector) and the purpose of the component is more clear.
  • Removed the limit of one static object per cell. Now cells can have any number of static (not moving) and dynamic (moving) actors/objects. For example, a cell can now have a floor trap and a statue. This also simplified the code because now there’s just a list of actors/objects instead of a list plus the static object.
  • Extensive actor AI logging. Now the log very clearly shows why an actor chose a particular action and not others. Very handy for troubleshooting. The basic AI process is to 1) identify the potential actions and 2) select the best action. The logging explicitly indicates why potential actions were available or unavailable, and why potential actions were rejected or selected.
  • Added new effects: Cure Poison, Darkness, and Paralysis.
  • Added new items: Cure Poison Potion, Throwing Axe.
  • Damage type resistance. Physical materials now have explicit resistances to different damage types. This will be used to do things like making an axe more effective against a wooden door than a short sword.

The plan for next week is to replace Room Type-based room generation with Room Feature-based room generation and start on two new features: Enemy Alerts and Knowledge. The former provides visual indicators for whether enemies have seen the player and the former varies the descriptions of things based on the player’s knowledge.