Python Scripting

We have provided early access to this content in draft form in order to get you up and running. Check back soon for updates!
Getting started with Python

Python is an interpreted high-level programming language for general-purpose programming. Python has a design philosophy that emphasizes code readability, and a syntax that allows programmers to express concepts in fewer lines of code.

A few interesting references can be found here:

https://www.python.org/about/gettingstarted/

https://wiki.python.org/moin/

https://docs.python.org/2/

Scope & Limitations

Python is exposed as an “In Editor” only scripting language.  Scripts can be executed to automate tasks in the Unreal Editor, but won’t be able to be used during “Play” runtime.

As a general rule, anything that can be scripted with a Blueprint can be also accessed with Python with the exception of the Blueprint Class, Struct, and Enum that are created inside the Editor.

Only Class and Struct that are accessible in Blueprint are accessible in Python. As with native C++ code or Blueprint, the Unreal Object is garbage collected when unused.

Unreal requires the use of Python version 2.7

Enabling Python in Unreal

Activate the Python plugin

The Python plugin can be activated via the Plugins menu. Once activated, you will be able to execute Python script from the Editor.

Note: The Python plugin needs to be activated for each Project.

Edit -> Plugins -> Built-In -> Python Editor Script Plugin -> Enabled

EnablePythonPlugin


Unreal Studio Users

If you are an Unreal Studio user, you will have access to additional helper utilities.

The Editor Scripting Utilities plugin provides functions that help you with basic operations.

The API are simplest in their utilization and test a lot of edge cases for you. They are described later in this document.

EnablePlugins

Python Output Log

The Python log is linked to Unreal Engine 4 log. This is where you can start invoking Python commands and see output data as scripts are executed.

Window -> Developer Tools -> Output Log:

OutputLog

Executing Python scripts

Executing a Python Script from the File menu

Select the Python script (*.py) you would like to execute. Recent files executed will be available in the Recent Python Script menu.

File -> Execute Python Script:

ExecuteScript

Executing a Python Script from the Console | Cmd

You can enter the Console Command “py” to execute a Python file. You can also append your arguments if your script requires them:

ExecutePythonCommand

Tip: You can enter a Console Command via many places in Unreal: Output Log, Blueprint or by using the ‘` /~’ key (under Esc on your keyboard).

Executing a Python Script Line by Line

You can execute a single Python line of code in the Output Log | Python window by changing the Command Input Type from Cmd to Python

ExecutingScriptLineByLine

Run Python as a command line argument when launching the Unreal Editor

If you want to execute a Python script when you launch the Unreal Editor, launch the engine with ExecCmds=”py MyScript.py”.

Keep in mind that the script might start to execute before everything has finished to compile or load which can cause your script to work incorrectly  (ex: changing a level that is not completely loaded on startup).

Notes: Unreal Studio users will benefit from an extra utility that allows to overcome this potential problem.

Using a different version of Python with Unreal

Unreal Engine has been tested with Python 2.7.14.

You can use another version of Python by specifying the location of your Python folder with an environment variable entitled “UE_PYTHON_DIR” and recompile the Unreal Engine from its source code.

Basic Examples

The following examples require content to be downloaded from this location:

https://epicgames.box.com/v/Python-Examples under the “Basic Examples” folder

Hello world

print evaluates each expression in turn and writes the resulting object to standard output

hello_world.py

print “hello world”

Interfacing with the Unreal object

Import Unreal is the only Python ‘import’ command that is required to interface with Unreal Engine 4.

This should let you access several Unreal objects/classes as shown in the following examples:

unreal_hello_world.py

import unreal
unreal.log("hello world”)

unreal_object.py

import unreal
obj = unreal.MediaPlayer()
result = obj.open_file(“c:\MyFile.mov”)
print result

Listing all classes available through the Unreal object

To get the full list of of Unreal classes, use the dir function:

import unreal
print dir (unreal)

Listing variables and functions available from an Unreal object

To get the full list of variables and functions on a given Class, use the help function:

import unreal
help (unreal.MediaPlayer)

Unreal Core Types

When doing object manipulation, it is best to use the built-in Unreal objects as opposed to use external vector, math or other matrix computation libraries.Here is how to access this data:

vector.py

import unreal
v1 = unreal.Vector()
v1.x = 10
v2 = unreal.Vector(10, 20, 30)
v3 = (v1 + v2) * 2
print v3

Unreal Specificity and Caveats

Details Panel

Object properties shown in the Details Panel do not behave the same way as runtime (in game) properties. It might not be obvious at first, but that is how Unreal works.

 

Details

 

When you modify a property in the Details Panel, it is possible that some code is run in the background, which doesn’t occur at runtime.

Tracking and recording events for Undo / Redo is an example of that. That only happens in the editor and when you use the Detail Panel and interact with it by clicking on the interface. Obviously, that doesn’t happen at runtime (in game).

With Python in Unreal, if you want to change or inspect properties found in the Details Panel,you must call the set_editor_property and get_editor_property methods as opposed to access properties directly:

edit_property.py

import unreal
obj = unreal.MediaPlayer()
# this type of property modification might create different results than what a user might get while changing settings in the editor, we don’t recommend it
obj.play_on_open = True
# this type of property modification will do exactly the same as a user might get while changing settings in the editor, it’s the recommended method
obj.set_editor_property(“play_on_open”, True)
print obj.get_editor_property(“play_on_open”)
For C++ programmers

The behavior depends on the UPROPERTY keyword used. EditAnywhere, VisibleAnywhere, BlueprintReadWrite, set_editor_property calls the Pre/PostEditChangeProperty for you.

Undo/Redo scope

The editor of Unreal Engine 4 supports undo/redo transactions.This means that you can bundle large chunks of Python code inside a single undo/redo transaction, which can be useful in many cases. For example, changing a material on 200 objects, you don’t want 200 different undo transactions)

To create a new undo transaction use the scope ScopedEditorTransaction.

scoped_editor_transaction.py

import unreal
obj = unreal.MediaPlayer()
with unreal.ScopedEditorTransaction("My Transaction Test") as trans:
obj.set_editor_property(“play_on_open”, True)
obj.set_editor_property(“vertical_field_of_view”, 60)

Edit-> Undo History would now show this:

undoHistory

Note: However, not every operation can live in a undo/redo transaction. For example, you can’t undo after importing models in Unreal so importing with Python inside a undo transaction will most likely crash the editor.

Assets operations

If you need to script operations on assets, it is critical to avoid doing file manipulations on the file system like you could do in your file system (with Windows). This will break how assets that Unreal uses are linked between each other.

When you make changes to assets in the Content Browser, Unreal will do a lot of extra operations to update references, reconnect links etc...

With Python, if you want to move, delete, copy or rename assets contained in the Content Browser, use the function found in the AssetTools class.

If you are a Unreal Studio user, you can use the EditorScriptingUtilitites plugin (see section for Unreal Studio below)

Additional Scripting Utilities for Unreal Studio Users

If you are a Unreal Studio user, you will have access to an additional utility that provides API that are simpler in their utilisation and test a lot of edge cases for you.

Although you can do pretty much everything you need with Python in the free version of the Unreal Engine, some operations can require quite complicated scripts to be made. For example, renaming an asset could require knowledge of the internal code of Unreal Engine 4 that goes beyond doing a simple string change.

Enable the “Editor Scripting Utilities Plugin”

Make sure the plugin entitled Editor Scripting Utilities is enabled in your project.

EnableEditorScripting

Additional Libraries Provided by the Editor Scripting Utilities Plugin

The following libraries are available.

Tip:to list all methods and properties, use the help command as follows:

import unreal
help(unreal.EditorAssetLibrary)
help(unreal.EditorLevelLibrary)
help(unreal.EditorFilterLibrary)
etc..
unreal.EditorAssetLibrary

In Unreal Engine 4, an asset needs to be loaded before utilization. This library lets you load, save, rename etc. assets contained in the Content Browser.

Note: Once an asset is loaded in Unreal Engine 4, it will be loaded in memory until the editor is closed.

unreal.EditorLevelLibrary

In collaboration with unreal.EditorLoadingAndSavingUtils, unreal.EditorLevelLibrary let you modify, spawn, destroy actors from a level.

You can also create and save levels in your project.

unreal.EditorFilterLibrary

A library of functions to filter a list of actors and objects by name, tag, class, etc.

Run Python as a command line argument

With the plugin EditorScriptingUtilitites you can use 'ExecutePythonScript=' with the command line argument which will wait for the Editor to be fully loaded and idle before running the Python script.

This can be useful if you need to perform scripting operations on objects that are on a level that can take a while to load.

UE4Editor-Cmd.exe MyProject.uproject ExecutePythonScript="c:\my_script.py"


Sample Scripts for Unreal Studio Users

The following examples require content to be downloaded from this location:

https://epicgames.box.com/v/Python-Examples under the “Unreal Studio Examples” folder.

You will find script and content examples related to Unreal Studio workflows:

  • Imports a Datasmith file
  • Replace Material
  • Merge Actors
  • Level Editing
  • Content Browser
  • Convert Actors
  • Join Actors

How to try / install the sample scripts

The provided samples will expect content to be available in your Unreal Project. For example, some scripts will load materials, levels etc.

Loading assets in your Unreal project

A few sample scripts rely on *.uasset and *.umap files to work:

InstallSampleAssets

They must be loaded in Unreal prior to executing the Python script provided. Here is how to do it:

  1. Create a new Unreal Studio project
  2. Enable all necessary Python plugins (as instructed above)
  3. Close the Unreal Studio project.
  4. Add all the assets provided with the sample scripts in the [YourProject]/Content/ by using Windows Explorer (not Unreal)
  5. Start your project

At this point, you should see the provided Assets (*.uasset and *.umap files etc.) available in the Unreal Content Browser.

Assets paths defined in the scripts

In order to get them working correctly, you will need to make sure that the paths of the assets expected by those scripts are valid.

For example, in the code below, the script will try to load an asset at a very specific path:

base_folder = "/Game/"
destination = base_folder + "ContentBrowser/MyAsset_Renamed"

Make sure you edit the scripts so that paths are matching where you have loaded assets.