Working with Source Code (C# 4.0)
Accessing game data during runtime is possible by utilizing the generated source code.
This section provides examples using default class names, but it is possible to customize class names during the source code generation process. Additionally, this customization allows to avoid naming collisions with existing code.
Loading Game Data
The following C# code creates
GameData class and loads your game data into memory.
using System.IO; var fileStream = File.OpenRead("gamedata.json"); var gameData = new GameData(fileStream, GameData.Format.Json); fileStream.Dispose();
gamedata.json could be published game data or original database file (.gdjs or .gdmp).
You can access your documents as a list:
var characters = gameData.GetCharacters() // -> ReadOnlyList<Character> var characters = gameData.GetCharacters(onlyRoot: true) // -> ReadOnlyList<Character>
Or you can access specific documents by their
Id or Unique properties:
var character = gameData.GetCharacter(characterId); // -> Character var character = gameData.GetCharacterByName(characterName); // -> Character
Settings schemas are accessed by name:
var resetTime = gameData.LootSettings.ResetTime; // -> TimeSpan
Formulas are executed with Invoke method:
var reward = gameData.LootSettings.RewardFormula.Invoke() // -> int
Formula’s parameters are passed as arguments of
Generated Code Extensions
When generating source code for game data, the resulting C# classes are declared as partial. This means that the classes can be extended by the programmer to add custom functionality.
For example, let’s say that you have generated a
GameData class for your game data. This class contains properties and methods for accessing and manipulating the data. However, you want to add some custom functionality to this class, such as a method for getting specific documents by criteria.
To do this, you can create a new C# file and declare a partial class with the same name as the generated
GameData class. You can then define your custom method in this class, and it will be merged with the generated class at compile time.
Here is an example of how this could look:
In this example, the
GameData class is declared as partial, and two partial classes are defined with the same name: one generated by the source code generation process and one containing custom code added by the programmer.
By using partial classes in this way, you can extend the functionality of the generated classes without modifying the generated code directly. This allows you to keep your custom code separate from the generated code, making it easier to maintain and update your game data classes over time.
There is also two extension points on
partial void OnBeforeInitialize(); // Called after loading the data into lists and dictionaries and before processing references and marking documents read-only. partial void OnInitialize(); // Called after loading and prepping all data.