Writing Data-Driven Code in Unity : Variables

Hello there, I realize that I haven’t posted in here for the longest time! Work consumes a lot of my time so I haven’t really put a lot of work on blogging anything. I am on holidays so I thought it would be good to work on a few things just for the fun of it and also to learn more!! I will be posting about systems, practices or anything that I think might be useful for those who use Unity or Unreal! The next series of posts will be about data-driven code in Unity, which is something that I have been using for the past couple of years and I have found pretty handy in some cases.

I would like to start that data-driven code works perfectly whenever you want to make a prototype of your game! It helps you put the logic together pretty easily, however I highly recommend that for the next stage of your game to write scripts / components for the mechanics. The major reason is that using this approach could get messy and confusing, especially when working with other developers. I tend to use this approach mainly when I might have to handle small events in game easily (i.e. dead event of a player might require animation, sfx, other vfx, camera movement, A HUNDRED EXPLOSIONS!).

I shall begin with variables. These will help me store and gather data I need for other components. I will be able to easily edit them through the editor and transfer/update data in multiple scripts. A good example is player’s health, I can set it on an integer variable and access it for whenever they get hit or healed. At the same time I can pass that data to UI scripts that update a bar on the screen whenever the variable changes. To start I wrote a generic abstract class Variable, and I could go in detail but I think the code explains itself.

The next step is to then to extend/inherit from variable and create a class for primitive types : int, float, bool. I also tend to create one for string since sometimes I might need to transfer/edit this type of data (i.e. player tag or character name). Since the Variable class is generic all I had to do was to then extend it and tada!

One thing that might be important is that variables should have a unique id in certain occasions, especially if you are going to store them in a data structure (i.e. dictionary). And then there’s the onValueChanged action. I have found that using actions make things easier, especially when you want to link events that might require data for them to do what you want to do.

Well, that was easy! For the next post I intend to talk about how we can use these variables and how to create a modular event system that can help you put things together for a game pretty easily. Until then!

 

0 thoughts on “Writing Data-Driven Code in Unity : Variables

Leave a Reply

Your email address will not be published. Required fields are marked *