Event database in Unity

I used two useful, yet simple, data type tricks in Mr Mayor's Energy Crisis. The first one AnimationCurves for NonAnimations, the second one you're looking at right now.

Events!

There were many of them, 35 to be precise, and they needed to be stored somewhere. In a longer project I might have used JSON, CSV or one of my own custom formats from the past, but for a jam I needed something simpler and most importantly quicker to setup.
:thinking::bulb: Serialized objects!

Object?

C# objects are made out of a class like this one. EventData1.PNG You should know this.

If you make a public object out of the class, it won't show up in the inspector though.

EventDatabase1.PNG Trust me, nothing will show up.

Inspector1.PNG What did I tell you!

Serialized?

But if you add the [System.Serializable] attribute to the class, things will change.

EventData2.PNG Such a little thing

Inspector2.PNG Makes all the difference

What now, boss?

Well, lets make an array of events.

EventDatabase2.png More events!

And add a text variable to the event class with the [TextArea] attribute.

EventData3.PNG You'll see what the attribute does in the next bit.

Now editing multiple events in the editor is smooth sailing

Inspector3.PNG It expands the text area! Who would have thought!

So ah, how to use this thing?

We need to be able to find events from the database and easily access it. A linear search function will do as a quick and dirty solution for the first issue.

EventDatabase3.PNG Sometimes a simple for loop is all you need.

The second problem is trickier, but turning the database into a singleton takes care of it.

EventDatabase4.PNG If you don't know what this means, just wait and see.

And here is how to use the database from any script.

Usage1.PNG At this point you can do whatever you want with the data in the event object.

Possible improvements?

There are a few: * Use an enum to find events instead of the name string. This cuts down on typo related bugs. * Rather than using linear search you can sort the array at Start() based on the enum and then find events via direct index at O(1) time. Lightning fast, as they say in the industry.

Conclusion

Simple to code, easy to edit. That's about it and here is the code.

Cheers!