So for the game I’ve been working on, currently known as Trading Company, we added an element to the game for some random events to happen. There are currently two different types of these events, events that can happen on jobs, and events that can happen while travelling. Well the way the system was setup used a base RandomEvent class, and two other classes that derived from that for the RandomEventJob and RandomEventTravel.
Well then, for each actual event I create a class for the event that all followed a simple structure, it had a bunch of strings for the display information, and some random checks to choose what actually happens as a result of that event. Well as time went on, I found it was tedious to continually make each new class for a new event, when they were all very similar. I probably couldn’t make some more generic code or a function to set this up, but I liked the format I had.
So the solution I thought of was some kind of code generation, but I’d never tried to generate code before, or even really thought about it much. I did some research online, found lots of different complex methods and examples. After doing some experimentation however, I found it was easier than I originally thought.
Ultimately I created a .txt template of a random event, and any place where I needed to customize data I added my own tag surrounded by a ‘#’. So for example, where I needed the class name, the template looked like:
public class #ClassName#
{
//Stuff
}
So I did this for all the customized data in the class, then I wrote the code generation class, which was much easier than I originally thought it would be. All I did was load that file with a StreamReader, I loaded in the data to a big string, and did a .Replace() for all the tags I had created. Once that was done I just saved it with the name passed in with the .cs extension, and it was that simple.
After that all I did was create a custom editor that I could use to easily fill out all the information in one go. This allowed not only me to generate this random event easily, but anyone else unfamiliar with my code, or any designers to come in and add a new event.
Here’s what the editor looks like:
0 comments on “The Wonders of Code Generation”Add yours →