Using the API
You usually do not need to write any code to run the procedural generator. But sometimes, you might want extra control over the generator and writing a few lines of code might help you achieve your goals.
Using the On Level Generated
event
Sometimes you might only need to call a custom function after a level is generated. The easiest way to achieve this is to use the Events
section of the generator inspector and add a callback for the On Level Generated
event. The callback signature looks like this:
using Frigga;
using UnityEngine;
// Add this component to an object in the scene and call it from the On Level Generated event.
public class PostProcessing1 : MonoBehaviour
{
public void OnLevelGenerated(GeneratorResult result)
{
Debug.Log("The level was generated!");
Debug.Log($"The Theme that was used is named {result.Theme.name}");
}
}
Using the API
In some cases, you might want to control the complete flow of the generator. For example, you might want to show a loading screen before a level gets generated, and then hide it after a level is generated. In such cases, you can call the generator from code like this:
using System.Collections;
using Frigga;
using UnityEngine;
// INSTRUCTIONS:
// - Add this component to an object in the scene
// - Assign the Generator field
// - Make sure the "Generate On" field in the generator is set to "Manually"
// - Enter play mode
public class UsingTheApi : MonoBehaviour
{
public GeneratorBase Generator;
private void Awake()
{
StartCoroutine(StartGenerate());
}
protected virtual IEnumerator StartGenerate()
{
// Check that GenerateOn is set to Manually
if (Generator.GenerateOn != GenerateOn.Manually)
{
Debug.LogError("GenerateOn should be set to 'Manually' when a generator is called from a script.");
yield break;
}
// TODO: place your code here, before generator started, e.g. show a loading screen
Debug.Log("Before generator started");
// Generate the level asynchronously and get the result
var generatorEnumerator = Generator.StartGenerate();
yield return generatorEnumerator;
var result = generatorEnumerator.Result;
// TODO: place your code here, after generator done, e.g. initialize nav mesh
Debug.Log("After level generated");
}
}
Some of the examples use the FriggaGameManager
class which showcases how to call the generator from a script. Check that class if you want to see it used in action.