Signals in UnrealScript

Here’s an idiomatic UnrealScript example demonstrating signal handling:

class SignalHandler extends Object;

var bool bShouldExit;

function Initialize()
{
    // Register for game events that simulate signals
    class'GameEngine'.static.GetEngine().GameViewport.RegisterInputKey(
        "Escape", OnEscapePressed);
    class'GameEngine'.static.GetEngine().GameViewport.RegisterInputKey(
        "Q", OnQuitPressed);
}

function OnEscapePressed()
{
    `log("Escape key pressed (simulating SIGINT)");
    HandleSignal();
}

function OnQuitPressed()
{
    `log("Q key pressed (simulating SIGTERM)");
    HandleSignal();
}

function HandleSignal()
{
    `log("Signal received, preparing to exit...");
    bShouldExit = true;
}

function Tick(float DeltaTime)
{
    if (bShouldExit)
    {
        `log("Exiting...");
        ConsoleCommand("exit");
    }
}

defaultproperties
{
    bShouldExit=false
}

This UnrealScript example demonstrates a concept similar to signal handling in other languages. Since UnrealScript doesn’t have direct access to operating system signals, we simulate them using key presses within the Unreal Engine environment.

Here’s a breakdown of the code:

  1. We define a SignalHandler class that extends Object.

  2. The Initialize function registers input keys to simulate signals. In this case, we use the Escape key to simulate SIGINT and the Q key to simulate SIGTERM.

  3. OnEscapePressed and OnQuitPressed functions are called when the respective keys are pressed. They log a message and call HandleSignal.

  4. The HandleSignal function sets a flag bShouldExit to true, indicating that the game should prepare to exit.

  5. The Tick function, which is called every frame, checks if bShouldExit is true. If so, it logs an “Exiting…” message and uses ConsoleCommand("exit") to quit the game.

  6. In defaultproperties, we initialize bShouldExit to false.

To use this in an Unreal Engine game:

  1. Create a new UnrealScript file named SignalHandler.uc in your game’s Classes directory.
  2. Paste the above code into the file.
  3. Compile your game’s scripts.
  4. In your game’s main GameInfo or GameMode class, create an instance of SignalHandler and call its Initialize function when the game starts.

This example demonstrates how to handle “signals” (simulated by key presses) in UnrealScript, allowing for graceful shutdown of the game when certain keys are pressed. It’s important to note that this is a simulation of signal handling within the context of an Unreal Engine game, as UnrealScript doesn’t have direct access to operating system signals.