Environment Variables in UnrealScript
Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in UnrealScript.
class EnvironmentVariables extends Object;
var string FOO, BAR;
function Init()
{
// To set a key/value pair, we can use a class variable
FOO = "1";
// To get a value for a key, we can access the class variable
`log("FOO:" @ FOO);
`log("BAR:" @ BAR); // This will be empty as we haven't set it
}
function ListEnvironmentVariables()
{
local array<string> EnvVars;
local string EnvVar;
// In UnrealScript, we don't have direct access to system environment variables
// Instead, we can simulate it by creating our own list
EnvVars.AddItem("TERM_PROGRAM=UnrealEditor");
EnvVars.AddItem("PATH=/UnrealEngine/bin");
EnvVars.AddItem("SHELL=/bin/unrealscript");
EnvVars.AddItem("FOO=" $ FOO);
`log("Listing all environment variables:");
foreach EnvVars(EnvVar)
{
`log(Split(EnvVar, "=", true));
}
}
defaultproperties
{
FOO=""
BAR=""
}
In UnrealScript, we don’t have direct access to system environment variables like in other languages. Instead, we can simulate this behavior by using class variables and custom functions.
To set a key/value pair, we use class variables. To get a value for a key, we simply access these variables. If a variable hasn’t been set, it will return an empty string.
FOO = "1";
`log("FOO:" @ FOO);
`log("BAR:" @ BAR);
To list all key/value pairs in the environment, we create a custom function that simulates this behavior. In this example, we’re using an array of strings to store our “environment variables”:
function ListEnvironmentVariables()
{
local array<string> EnvVars;
local string EnvVar;
EnvVars.AddItem("TERM_PROGRAM=UnrealEditor");
EnvVars.AddItem("PATH=/UnrealEngine/bin");
EnvVars.AddItem("SHELL=/bin/unrealscript");
EnvVars.AddItem("FOO=" $ FOO);
`log("Listing all environment variables:");
foreach EnvVars(EnvVar)
{
`log(Split(EnvVar, "=", true));
}
}
To run this in UnrealScript, you would typically call these functions from another class or script:
class MyGame extends GameInfo;
function PreBeginPlay()
{
local EnvironmentVariables EnvVars;
super.PreBeginPlay();
EnvVars = new class'EnvironmentVariables';
EnvVars.Init();
EnvVars.ListEnvironmentVariables();
}
This would output something like:
FOO: 1
BAR:
Listing all environment variables:
TERM_PROGRAM
PATH
SHELL
FOO
Remember that in UnrealScript, we’re simulating environment variables. In a real UnrealScript environment, you would typically use configuration files or other UnrealEngine-specific methods to manage game settings and configurations.