### Configure Unreal Engine Python Plugin (INI) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Illustrates how to configure the Unreal Engine Python plugin by adding a `[Python]` stanza to the `Config/DefaultEngine.ini` file. This example sets the `Home` parameter to specify the Python installation path, useful for custom environments. ```ini [Python] Home = C:/FooBar/Python36 ``` -------------------------------- ### Install pycollada Module Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/SnippetsForStaticAndSkeletalMeshes.md Instructions to install the `pycollada` Python module, which is a prerequisite for parsing Collada files as demonstrated in the skeletal mesh import example. ```bash pip install pycollada ``` -------------------------------- ### Complex Example: Line Tracing with Enums and Output Values Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Showcases an advanced usage of Unreal Engine Python, demonstrating how to perform a line trace. This example includes importing specific enums (`ETraceTypeQuery`, `EDrawDebugTrace`), passing keyword arguments, and handling multiple return values where 'output values' are appended after the primary return value. ```python import unreal_engine as ue from unreal_engine import FVector, FRotator, FTransform, FHitResult from unreal_engine.classes import ActorComponent, ForceFeedbackEffect, KismetSystemLibrary, WidgetBlueprintLibrary from unreal_engine.enums import EInputEvent, ETraceTypeQuery, EDrawDebugTrace ... is_hitting_something, hit_result = KismetSystemLibrary.LineTraceSingle_NEW(self.actor, self.actor.get_actor_location(), FVector(300, 300, 300), ETraceTypeQuery.TraceTypeQuery1, DrawDebugType=EDrawDebugTrace.ForOneFrame) if is_hitting_something: ue.log(hit_result) ``` -------------------------------- ### Adding a Widget with WidgetBlueprintLibrary Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Illustrates how to create and add a UI widget in Unreal Engine using the `WidgetBlueprintLibrary.Create` static method. This example is typically used within a Python class's `begin_play` method to instantiate a widget blueprint. ```python from unreal_engine.classes import WidgetBlueprintLibrary class PythonFunnyActor: def begin_play(self): WidgetBlueprintLibrary.Create(self.uobject, ue.find_class('velocity_C')) ``` -------------------------------- ### Importing and Using Unreal Engine Classes Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Demonstrates how to import Unreal Engine classes like `ActorComponent`, `ForceFeedbackEffect`, and `KismetSystemLibrary` as Python classes using the `unreal_engine.classes` module. It shows examples of calling instance methods (e.g., `GetComponentsByClass`) and static class methods (e.g., `KismetSystemLibrary.GetObjectName`). ```python from unreal_engine.classes import ActorComponent, ForceFeedbackEffect, KismetSystemLibrary ... components = self.uobject.get_owner().GetComponentsByClass(ActorComponent) ... self.force_feedback = ue.load_object(ForceFeedbackEffect, '/Game/vibrate') self.uobject.get_player_controller().ClientPlayForceFeedback(self.force_feedback) ... name = KismetSystemLibrary.GetObjectName(self.actor) ``` -------------------------------- ### Example Unreal Engine Asset Reference Source: https://github.com/20tab/unrealenginepython/blob/master/docs/ManagingAssets.md Provides a concrete example of an asset reference for a material named 'Foobar' located in '/Game/Materials/Mat001'. This demonstrates how the naming convention translates to a real-world asset path. ```text /Game/Materials/Mat001.Foobar ``` -------------------------------- ### Spawn Actors in Unreal Engine Editor World (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Shows how to spawn `Actor` and `Character` instances directly into the Unreal Engine editor world using `ue.get_editor_world()` and `world.actor_spawn()`. This allows for programmatic scene setup within the editor. ```python import unreal_engine as ue from unreal_engine.classes import Actor, Character from unreal_engine import FVector, FRotator world = ue.get_editor_world() actor000 = world.actor_spawn(Actor, FVector(0, 0, 0), FRotator(0, 0, 0)) character000 = world.actor_spawn(Character, FVector(100, 100, 100), FRotator(0, 0, 0)) ``` -------------------------------- ### Create PySide2 Widget to Display Unreal Engine Asset Thumbnails Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This example illustrates how to build a PySide2 QWidget that queries Unreal Engine assets using `FARFilter` (specifically SkeletalMesh and Material assets) and displays their thumbnails. It demonstrates asset data retrieval, thumbnail extraction, and rendering within a PySide2 GUI, attaching the widget to the Unreal Engine editor's root window. ```python import ueqt from PySide2 import QtCore, QtWidgets, QtGui import unreal_engine as ue from unreal_engine import FARFilter _filter = FARFilter() _filter.class_names = ['SkeletalMesh', 'Material'] class MyWidget(QtWidgets.QWidget): def __init__(self): super().__init__() self.vertical = QtWidgets.QVBoxLayout() self.scroll = QtWidgets.QScrollArea() self.content = QtWidgets.QWidget() self.scroll.setWidget(self.content) self.scroll.setWidgetResizable(True) self.layout = QtWidgets.QVBoxLayout() for asset_data in ue.get_assets_by_filter(_filter, True): try: thumbnail = asset_data.get_thumbnail() except: continue label = QtWidgets.QLabel() data = thumbnail.get_uncompressed_image_data() image = QtGui.QImage(data, 256, 256, QtGui.QImage.Format_RGB32) label.setPixmap(QtGui.QPixmap.fromImage(image).scaled(256, 256)) self.layout.addWidget(label) self.content.setLayout(self.layout) self.vertical.addWidget(self.scroll) self.setLayout(self.vertical) widget = MyWidget() widget.resize(800, 600) widget.show() root_window = ue.get_editor_window() root_window.set_as_owner(widget.winId()) ``` -------------------------------- ### Creating a New Unreal Engine Struct Instance Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Demonstrates the basic instantiation of a new Unreal Engine struct using the `unreal_engine.structs` module. This creates an empty instance of the specified struct. ```python from unreal_engine.structs import TerrificStruct ts = TerrificStruct() ``` -------------------------------- ### Spawn Blueprint-Generated Classes in Unreal Engine (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Illustrates the initial setup for spawning an actor from a Blueprint asset. It emphasizes that you need to retrieve the class generated by the blueprint, not the blueprint asset itself, for successful spawning. ```python import unreal_engine as ue from unreal_engine.classes import Blueprint from unreal_engine import FVector, FRotator world = ue.get_editor_world() ``` -------------------------------- ### Clone UnrealEnginePython Repository Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This command clones the official UnrealEnginePython GitHub repository to your local machine. It is the first step for a source-based installation, providing access to the latest updates and the plugin's source code for compilation. ```sh git clone https://github.com/20tab/UnrealEnginePython ``` -------------------------------- ### Define a Python Class for Unreal Engine Actor Behavior Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This Python code defines a `Hero` class intended to manage an Unreal Engine actor's behavior. It demonstrates the `begin_play` method, called at game start, and the `tick` method, which executes every frame. The `tick` method shows how to retrieve, modify, and set an actor's location using `self.uobject` to achieve movement along the Z-axis. ```python import unreal_engine as ue ue.log('Hello i am a Python module') class Hero: # this is called on game start def begin_play(self): ue.log('Begin Play on Hero class') # this is called at every 'tick' def tick(self, delta_time): # get current location location = self.uobject.get_actor_location() # increase Z honouring delta_time location.z += 100 * delta_time # set new location self.uobject.set_actor_location(location) ``` -------------------------------- ### Get/Set Material Instance Parameters (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Material_API.md Provides examples of methods to get and set different types of parameters (scalar, vector, texture) on a `Material Instance` using their parameter names. ```python # retuns a float material_instance.get_material_scalar_parameter('Parameter name') # returns a FVector material_instance.get_material_vector_parameter('Parameter name') # returns a Texture material_instance.get_material_texture_parameter('Parameter name') material_instance.set_material_scalar_parameter('Parameter name', float) material_instance.set_material_vector_parameter('Parameter name', FVector) material_instance.set_material_texture_parameter('Parameter name', Texture) ``` -------------------------------- ### Install Python Libraries for SVG Path Parsing Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/SnippetsForStaticAndSkeletalMeshes.md This command installs the necessary Python libraries (`svgpathtools`, `svgwrite`, `numpy`) required for parsing SVG files. These libraries are essential for converting SVG path data into a format usable for generating animations in Unreal Engine, specifically for the root motion animation example. ```bash pip install svgpathtools svgwrite numpy ``` -------------------------------- ### Initialize Unreal Engine Python Environment Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This Python script initializes the Unreal Engine Python environment, importing the `unreal_engine` module and printing a confirmation message. It serves as a basic test to ensure the plugin is working correctly after installation. ```Python import unreal_engine as ue print('Hello i am your pipeline automator') ``` -------------------------------- ### Listing and Querying Unreal Engine Assets Source: https://github.com/20tab/unrealenginepython/blob/master/docs/PythonConsole.md This example demonstrates various methods to retrieve assets within Unreal Engine. It shows how to get assets under a specific path (optionally recursive), filter assets by a given class name (including subclasses), and retrieve assets currently selected in the Content Browser. These functions are crucial for asset management and automation. ```python # get the assets under the specified path assets = unreal_engine.get_assets(path[, recursive]) # get all the assets implementing the specified class (class_name is a string, like 'SkeletalMesh') assets = unreal_engine.get_assets_by_class(class_name[, includes_subclasses]) # get the assets currently selected in the content browser assets = unreal_engine.get_selected_assets() ``` -------------------------------- ### Initializing Unreal Engine Struct Fields Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Illustrates how to create an Unreal Engine struct instance and initialize some of its fields directly during instantiation. Fields are set using keyword arguments, providing a convenient way to populate struct data upon creation. ```python from unreal_engine.structs import TerrificStruct ts = TerrificStruct(Foo='Bar', Test=17.22) ``` -------------------------------- ### Importing the unreal_engine Module Source: https://github.com/20tab/unrealenginepython/blob/master/docs/UnrealEngineModule.md Demonstrates the standard ways to import the `unreal_engine` module into a Python script, enabling access to its functionalities. It includes both a direct import and an example of aliasing the module for shorter references. ```py import unreal_engine import unreal_engine as ue ``` -------------------------------- ### Unreal Engine Python Core API Reference Source: https://github.com/20tab/unrealenginepython/blob/master/README.md A reference for key functions and methods exposed by the Unreal Engine Python plugin, covering primitives, object/asset referencing, and UObject methods for interaction and serialization. ```APIDOC Primitives and Math Functions: FVector FRotator FQuat FColor FHitResult Object/Asset Referencing Functions (ue module): find_class(class_name: str) -> UClass find_struct(struct_name: str) -> UStruct find_object(object_path: str) -> UObject load_struct(path: str) -> UStruct load_class(path: str) -> UClass load_object(class_or_struct: UClass|UStruct, path: str) -> UObject UObject Methods: uobject.as_dict() -> dict Description: Serializes the uobject to a Python dictionary. uobject.call(function_name: str) Description: Calls a Blueprint function or custom event. uobject.call_function(function_name: str, *args, **kwargs) -> any Description: Calls a Blueprint function, allowing for return values and Python arguments. uobject.get_property(property_name: str) -> any Description: Retrieves the value of a public variable/property from the Blueprint. uobject.get_up_vector() -> FVector Description: Returns the 'up' vector of the UObject. uobject.get_actor_location() -> FVector Description: Returns the current location of the actor associated with the UObject. uobject.set_actor_location(new_location: FVector) Description: Sets the new location for the actor associated with the UObject. ``` -------------------------------- ### Spawn and Configure New PyActor at Runtime (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Demonstrates how to dynamically spawn a new `PyActor` at runtime in Unreal Engine. It sets its initial location, adds a sphere component as the root, assigns a static mesh, and configures its associated Python module and class. ```python class SuperHero: def begin_play(self): # spawn a new PyActor new_actor = self.uobject.actor_spawn(ue.find_class('PyActor'), Fvector(0, 0, 0),FRotator(0, 0, 90)) # add a sphere component as the root one static_mesh = new_actor.add_actor_root_component(ue.find_class('StaticMeshComponent'), 'SphereMesh') # set the mesh as the Sphere asset static_mesh.call('SetStaticMesh /Engine/EngineMeshes/Sphere.Sphere') # set the python module new_actor.set_property('PythonModule', 'gameclasses') # set the python class new_actor.set_property('PythonClass', 'Vertical') ``` -------------------------------- ### Installing BVH Python Library via Pip Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/SnippetsForStaticAndSkeletalMeshes.md This command installs the `bvh` Python library using pip, the Python package installer. This library is essential for parsing BVH (Biovision Hierarchy) motion capture files, enabling their use within Python applications. ```bash pip install bvh ``` -------------------------------- ### Clone Unreal Engine Python Plugin Repository Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Clones the Unreal Engine Python plugin repository from GitHub into the current directory, typically the project's Plugins folder, as part of a source installation for both MacOSX and Linux. ```sh git clone https://github.com/20tab/UnrealEnginePython ``` -------------------------------- ### Unreal Engine Python Asset Loading (load_struct) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Illustrates how to load an Unreal Engine struct asset from a specified path using `ue.load_struct()`. The loaded struct data can then be converted into a Python dictionary using the `as_dict()` method for easier manipulation. ```python a_struct_data = ue.load_struct('/Game/Data') ue.log(a_struct_data.as_dict()) ``` -------------------------------- ### Create New Material Using Factory (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Material_API.md Illustrates creating a new `Material` asset using the `MaterialFactoryNew` class in Python, which is a more robust way to create assets in the editor. Includes an example of deleting the asset. ```python from unreal_engine.classes import MaterialFactoryNew import unreal_engine as ue factory = MaterialFactoryNew() new_material = factory.factory_create_new('/Game/Materials/NewFunnyMaterial') # destroy the asset ue.delete_asset(new_material.get_path_name()) ``` -------------------------------- ### Unreal Engine Python: Detailed Archetype Property Modification Process Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Explains the detailed steps involved in modifying an archetype property, including pre/post edit change notifications and iterating through instances. This verbose process is what the shortcut method encapsulates for convenience. ```python your_blueprint.GeneratedClass.get_cdo().CharacterMovement.pre_edit_change('MaxWalkSpeed') your_blueprint.GeneratedClass.get_cdo().CharacterMovement.set_property('MaxWalkSpeed', 600.0) your_blueprint.GeneratedClass.get_cdo().CharacterMovement.post_edit_change_property('MaxWalkSpeed') for instance in your_blueprint.GeneratedClass.get_cdo().CharacterMovement.get_archetype_instances(): instance.pre_edit_change('MaxWalkSpeed') instance.set_property('MaxWalkSpeed', 600.0) instance.post_edit_change_property('MaxWalkSpeed') ``` -------------------------------- ### Get Hit Result Under Cursor in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Retrieves the world point located directly under the mouse cursor. Refer to the Navigation section in the main README for an example usage. ```python hit = self.uobject.get_hit_result_under_cursor(channel) ``` -------------------------------- ### Initialize PySide2 Application and Unreal Engine Ticker Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This snippet demonstrates how to set up a basic PySide2 QApplication and integrate it with Unreal Engine's ticker system. The `ticker_loop` function processes PySide2 events, allowing a PySide2 GUI to run and remain responsive within the UE4 editor environment. ```python import sys import unreal_engine as ue import PySide2 from PySide2 import QtWidgets app = QtWidgets.QApplication(sys.argv) def ticker_loop(delta_time): app.processEvents() return True ticker = ue.add_ticker(ticker_loop) ``` -------------------------------- ### Destroy PyActor on Overlap in Unreal Engine (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/README.md An example of a `PyActor` (represented by the `Ball` class) that destroys itself when another actor overlaps with it. It demonstrates printing messages on begin play and collision, then calling `actor_destroy()` on the `uobject`. ```python class Ball: def begin_play(self): ue.print_string('Hello') def on_actor_begin_overlap(self, other_actor): ue.print_string('Collided with ' + other_actor.get_name()) self.uobject.actor_destroy() ``` -------------------------------- ### Get Unreal Engine Asset Reference with Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/ManagingAssets.md Demonstrates how to obtain a reference to a specific Unreal Engine asset using the `unreal_engine.get_asset` function in Python. The example also shows how to log the asset's representation and its properties for debugging or inspection. ```python import unreal_engine as ue # get the Mat001.Foobar asset material = ue.get_asset('/Game/Materials/Mat001.Foobar') # print material repr ue.log(material) # print material properties ue.log(material.properties()) ``` -------------------------------- ### Retrieve Unreal Engine Class Reference in Python Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This example shows how to use `unreal_engine.find_class` to obtain a reference to an Unreal Engine class, such as 'TextRenderComponent'. This function internally leverages Unreal's C++ reflection system and maps the found UObject to a special `ue_PyUObject` in Python, which is then cached for efficient access. ```python text_render_component = unreal_engine.find_class('TextRenderComponent') ``` -------------------------------- ### Access Python Proxy Class from Unreal Engine UObject Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This example demonstrates how to retrieve the Python class instance (proxy) associated with an Unreal Engine UObject using the `get_py_proxy()` method. This is crucial for interacting with Python-defined methods and properties when you only have a reference to the underlying UObject, enabling seamless communication between C++ UObjects and their Python counterparts. ```python import unreal_engine as ue class Explosive: 'Python representation for PyExplosiveActor in UE4' def go_boom(self): # do python stuff to explode ... self.uobject.destory() class BadGuy: 'Python reprsentation for PyBadGuyActor in UE4' def ignite_bomb(self, delay): bomb = self.uobject.MyBomb py_bomb = bomb.get_py_proxy() py_bomb.go_boom() ``` -------------------------------- ### Unreal Engine IPlugin Class Methods (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Plugin_API.md Illustrates how to retrieve various properties of an `IPlugin` instance, such as its name, base directory, content directory, descriptor file name, mounted asset path, and content/enabled status, using Python. ```python import unreal_engine paper2d = ue.find_plugin('Paper2D') # the name of the plugin name = paper2d.get_name() base_dir = paper2d.get_base_dir() content_dir = paper2d.get_content_dir() descriptor_file_name = paper2d.get_descriptor_file_name() mounted_asset_path = paper2d.get_mounted_asset_path() can_contain_content = paper2d.can_contain_content() is_enabled = paper2d.is_enabled() ``` -------------------------------- ### Configure Unreal Engine Input Action Mappings with Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Settings.md This Python example illustrates how to programmatically modify Unreal Engine's input system by adding new action mappings. It accesses the `InputSettings` mutable default object, creates `InputActionKeyMapping` instances with specific action names and keys (e.g., 'Kill' with Alt+X, 'Explode' with Y), and then saves the updated configuration. ```python import unreal_engine as ue from unreal_engine.classes import InputSettings from unreal_engine.structs import InputActionKeyMapping, Key inp = ue.get_mutable_default(InputSettings) km = InputActionKeyMapping() km.ActionName = 'Kill' key = Key() key.KeyName = 'x' km.Key = key km.bAlt = True km2 = InputActionKeyMapping() km2.ActionName = 'Explode' key = Key() key.KeyName = 'y' km2.Key = key km2.bAlt = False inp.ActionMappings = [km, km2] inp.save_config() ``` -------------------------------- ### Creating and Configuring a BlendSpace1D Asset in Unreal Engine (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This Python code creates a 1D BlendSpace asset in Unreal Engine, assigning a target skeleton and configuring blend parameters like 'Speed' (0-300). It then maps imported animation sequences (idle, walk, run) to specific sample values within the BlendSpace, enabling smooth transitions. The snippet also includes calls to open/close the asset in the editor and save the package. ```Python from unreal_engine.classes import BlendSpaceFactory1D from unreal_engine.structs import BlendSample, BlendParameter from unreal_engine import FVector blend_space_factory = BlendSpaceFactory1D() # you need to assign the related Skeleton blend_space_factory.TargetSkeleton = slicer_mesh.Skeleton # create the asset slicer_locomotion = blend_space_factory.factory_create_new('/Game/Kaiju/Slicer/Animations/slicer_locomotion') ue.open_editor_for_asset(slicer_locomotion) # set blend parameters slicer_locomotion.modify() slicer_locomotion.BlendParameters = BlendParameter(DisplayName='Speed', Min=0, Max=300, GridNum=2) # assign animations # 0 -> idle # 150 -> walk # 300 -> run # mark them as 'valid' explicitely ! slicer_locomotion.SampleData = [BlendSample(Animation=animation_idle, SampleValue=FVector(0, 0, 0), bIsValid=True, RateScale=1), BlendSample(Animation=animation_walk, SampleValue=FVector(150, 0, 0), bIsValid=True, RateScale=1), BlendSample(Animation=animation_run, SampleValue=FVector(300, 0, 0), bIsValid=True, RateScale=1)] # compute blend space and update the editor preview slicer_locomotion.post_edit_change() slicer_locomotion.save_package() ue.close_editor_for_asset(slicer_locomotion) ``` -------------------------------- ### Create Material Instance Using Factory (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Material_API.md Illustrates creating a `MaterialInstanceConstant` using the `MaterialInstanceConstantFactoryNew` class, allowing the specification of an initial parent material. ```python from unreal_engine.classes import Material, MaterialInstanceConstantFactoryNew factory = MaterialInstanceConstantFactoryNew() # get a reference to a parent material parent_material = ue.load_object(Material, '/Game/MainMaterial') factory.InitialParent = parent_material child_material = factory.factory_create_new('/Game/ChildMaterial') ``` -------------------------------- ### Verify Matplotlib Installation in Unreal Engine Python Console Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/PlottingGraphsWithMatplotlibAndUnrealEnginePython.md This simple Python command is executed within the Unreal Engine Python Console to verify that the Matplotlib library has been successfully installed and is accessible. If no import error occurs, the installation is confirmed, indicating Matplotlib is ready for use. ```python import matplotlib ``` -------------------------------- ### Discovering and Referencing Unreal Engine Plugins (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Plugin_API.md Demonstrates how to list all discovered or enabled plugins, and find a specific plugin by name using the `unreal_engine` module's plugin management functions. ```python import unreal_engine # get the list of all discovered plugins plugins_list = unreal_engine.get_discovered_plugins() # get the list of enabled plugins plugins_list = unreal_engine.get_enabled_plugins() # name is the string name of the plugin (like 'UnrealEnginePython' or 'Paper2D') plugin = unreal_engine.find_plugin(name) ``` -------------------------------- ### Install Matplotlib using System Python Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/PlottingGraphsWithMatplotlibAndUnrealEnginePython.md These shell commands install the Matplotlib library using a system-wide Python installation. They are typically used on Linux/Mac systems or when a non-embedded Python distribution is preferred. The specific command depends on the user's system configuration and how Python is aliased. ```sh pip3 install matplotlib ``` ```sh pip install matplotlib ``` -------------------------------- ### Install Matplotlib for Embedded Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/PlottingGraphsWithMatplotlibAndUnrealEnginePython.md This shell command installs the Matplotlib library specifically for the embedded Python distribution within Unreal Engine. The '--target .' flag ensures that the library is installed directly into the current directory, preventing it from being placed in a 'Lib/site-packages' subdirectory. ```sh ./python.exe -m pip install --target . matplotlib ``` -------------------------------- ### Import Texture Asset into Unreal Engine via Python Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This Python snippet demonstrates how to construct a file path for a texture and then import it into Unreal Engine using the `texture_factory.factory_import_object` function, specifying the target content path. ```python slicer_texture_orm_tga = os.path.join(kaiju_assets_dir, 'Textures/slicer_OcclusionRoughnessMetallic.tga') slicer_texture_orm = texture_factory.factory_import_object(slicer_texture_orm_tga, '/Game/Kaiju/Slicer/Textures') ``` -------------------------------- ### Spawn Actor in Unreal Engine Editor World Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This example illustrates how to programmatically spawn an actor (an instance of a blueprint) directly into the Unreal Engine editor's world. It first retrieves a reference to the current editor world using `ue.get_editor_world()` and then uses the `world.actor_spawn()` method, providing the blueprint's generated class and a desired spawn location (FVector). ```python world = ue.get_editor_world() world.actor_spawn(slicer_bp.GeneratedClass, FVector(17, 22, 30)) ``` -------------------------------- ### Implement Asyncio-based Streaming Radio Component in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/AsyncIOAndUnrealEngine.md This comprehensive example demonstrates how to create an Unreal Engine actor component that streams audio from an Icecast/Shoutcast server using asyncio, aiohttp, and mpg123. It integrates with Unreal Engine's audio system, handles component initialization and cleanup, and includes robust exception management for the streaming coroutine. ```python import ue_asyncio import asyncio import aiohttp import unreal_engine as ue from unreal_engine.classes import SoundWaveProcedural, AudioComponent import mpg123 import os class RadioStreaming: def initialize_component(self): ue.print_string('Hello') self.actor = self.uobject.get_owner() self.audio = self.actor.get_actor_component_by_type(AudioComponent) self.audio.Sound = SoundWaveProcedural() self.audio.Sound.Duration = 10000 # if you do not have libmpg123 in the system path, specify its absolute location here # self.mp3 = mpg123.Mpg123(library_path=os.path.join(ue.get_content_dir(), 'libmpg123-0.dll')) self.mp3 = mpg123.Mpg123() self.coroutine = asyncio.ensure_future(self.stream('http://178.32.136.160:8050')) self.coroutine.add_done_callback(self.check_exception) def check_exception(self, coro): if coro.cancelled(): return exc = coro.exception() if exc: raise exc async def stream(self, url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: ue.log_warning('start of stream') while True: chunk = await response.content.read(4096) if not chunk: break self.mp3.feed(chunk) if not self.audio.IsPlaying(): rate, channels, encoding = self.mp3.get_format() self.audio.Sound.SampleRate = rate self.audio.Sound.NumChannels = channels self.audio.Play() for frame in self.mp3.iter_frames(): self.audio.Sound.queue_audio(frame) def end_play(self, reason): ue.log_warning('end of stream') self.coroutine.cancel() ``` -------------------------------- ### Perform HTTP GET Request with Basic Polling in Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Http_API.md Shows how to make an HTTP GET request and poll its status using `get_status()` to determine completion. Once the status indicates completion (value >= 2), the response is retrieved and processed. ```python from unreal_engine import IHttpRequest import json request = IHttpRequest('GET', 'http://httpbin.org/user-agent') # run the request request.process_request() # check its status if request.get_status() >= 2: response = request.get_response() data = json.loads(response.get_content_as_string()) ue.log(data['user-agent']) ``` -------------------------------- ### Perform HTTP GET Request with Event Callback in Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Http_API.md Demonstrates how to make an HTTP GET request using `IHttpRequest` and handle the response asynchronously via a callback function bound to the `OnProcessRequestComplete` event. This is the recommended 'pythonic' approach for non-blocking operations. ```python from unreal_engine import IHttpRequest import json request = IHttpRequest('GET', 'http://httpbin.org/user-agent') def response_received(request, response, success): data = json.loads(response.get_content_as_string()) ue.log(data['user-agent']) # bind OnProcessRequestComplete event to the response_received callable request.bind_on_process_request_complete(response_received) # run the request request.process_request() ``` -------------------------------- ### Get Unreal Engine Asset Dependencies with Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/MigrateAssets.md This Python snippet demonstrates how to retrieve all recursive dependencies for a selected Unreal Engine asset. It uses `unreal_engine.get_selected_assets()` to get the initial asset and `unreal_engine.get_asset_dependencies()` to find its references, excluding engine and script paths. The `recursive_deps` function builds a comprehensive list of all dependent package paths required for migration. ```python import unreal_engine as ue # get the currently selected asset asset = ue.get_selected_assets()[0] # retrieve the package path package_path = asset.get_outermost().get_path_name() print(package_path) def recursive_deps(pkg_path, deps): deps.append(pkg_path) for _dep in ue.get_asset_dependencies(pkg_path): if _dep not in deps: if not _dep.startswith('/Engine') and not _dep.startswith('/Script'): recursive_deps(_dep, deps) deps = [] recursive_deps(package_path, deps) print(deps) ``` -------------------------------- ### Compile and Save Unreal Engine Blueprint (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This snippet demonstrates how to compile and save an Unreal Engine Blueprint programmatically using the `unreal_engine` Python module. It ensures that all changes made to the blueprint are applied and persisted to disk. ```python # compile and save ue.compile_blueprint(anim_bp) anim_bp.save_package() ``` -------------------------------- ### Get All Actor Components in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Retrieves the list of all components mapped to the actor. ```python components = uobject.get_actor_components() ``` -------------------------------- ### Create Material Instance with Shortcut (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Material_API.md Shows a simplified shortcut to create a `MaterialInstanceConstant` using `ue.create_material_instance`, which automatically names the instance based on its parent. ```python import unreal_engine as ue # the material instance will get the name of the parent with the _inst suffix material_instance = ue.create_material_instance(new_material) ``` -------------------------------- ### Get Component by Type in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Returns the first component (of an actor) of the specified type. ```python component = uobject.get_component_by_type(uclass) ``` -------------------------------- ### Complete UE4 Landscape Creation and Import Workflow (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Landscape_API.md This comprehensive Python example demonstrates the full process of creating a random heightmap, expanding it to the optimal dimensions for a UE4 landscape, spawning a Landscape actor, and finally importing the processed heightmap data into the newly created landscape. It also sets the actor's scale. ```python import unreal_engine as ue import struct import random from unreal_engine.classes import Landscape width = 1024 height = 1024 heightmap = [] for y in range(0, height): for x in range(0, width): heightmap.append(random.randint(0, 65535)) data = struct.pack('{0}H'.format(width * height), *heightmap) quads_per_section = 63 number_of_sections = 1 components_x = 8 components_y = 8 fixed_data = ue.heightmap_expand(data, width, height, quads_per_section * number_of_sections * components_x + 1, quads_per_section * number_of_sections * components_y + 1) landscape = ue.get_editor_world().actor_spawn(Landscape) landscape.landscape_import(quads_per_section, number_of_sections, components_x, components_y, fixed_data) landscape.set_actor_scale(1,1,1) ``` -------------------------------- ### Get Input Axis Value in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Retrieves the current value of a specified input axis. ```python value = uobject.get_input_axis('axis') ``` -------------------------------- ### Execute Unreal Engine Python Unit Tests Source: https://github.com/20tab/unrealenginepython/blob/master/README.md This snippet provides the command to run the unit tests included with the Unreal Engine Python plugin. It's executed from the UE4 Python console and is useful for verifying the plugin's functionality, especially when developing or adding new features. ```python import unreal_engine as ue ue.py_exec(ue.find_plugin('UnrealEnginePython').get_base_dir() + '/run_tests.py') ``` -------------------------------- ### Get Actor Bounds in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Obtains the bounding box of an object, returning both its location and extents as vectors. ```python location, extents = uobject.get_actor_bounds() ``` -------------------------------- ### Unreal Engine Python: Reflection-based Function Calls Source: https://github.com/20tab/unrealenginepython/blob/master/README.md Shows how to call Unreal Engine UObject functions using Python's `__getattr__` (dot notation), which internally uses `call_function` via reflection. This also applies to K2_ functions, providing a convenient way to interact with Unreal's API. ```python vec = self.uobject.GetActorRightForward() ``` ```python vec = self.uobject.call_function('GetActorRightForward') ``` ```python vec = self.uobject.GetActorLocation() ``` ```python vec = self.uobject.call_function('K2_GetActorLocation') ``` -------------------------------- ### Perform Single Line Trace in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Performs a single line trace by channel from a start to an end point. ```python hit = uobject.line_trace_single_by_channel(start, end, channel) ``` -------------------------------- ### Connect Animation Blueprint State Machine Nodes (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This snippet demonstrates how to programmatically connect states within an Unreal Engine Animation Blueprint's state machine using Python. It establishes transitions between an entry state, locomotion, bored, and attack states by connecting their respective input and output pins. ```python entry_state = state_machine.EditorStateMachineGraph.Nodes[0] # Entry to Locomotion entry_state.node_find_pin('Entry').connect(locomotion_state.node_find_pin('In')) # Locomotion to Bored locomotion_state.node_find_pin('Out').connect(bored_state.node_find_pin('In')) # Bored to Locomotion bored_state.node_find_pin('Out').connect(locomotion_state.node_find_pin('In')) # Locomotion to Attack locomotion_state.node_find_pin('Out').connect(attack_state.node_find_pin('In')) # Attack to Locomotion attack_state.node_find_pin('Out').connect(locomotion_state.node_find_pin('In')) ``` -------------------------------- ### Delete Unreal Engine Assets with Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/ManagingAssets.md Provides an example of how to remove an asset from the Unreal Engine project using `ue.delete_asset`. ```python ue.delete_asset('/Game/NewMaterials/Mat001.FooBarUpdated') ``` -------------------------------- ### Importing and Scaling Multiple Animations in Unreal Engine (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/tutorials/YourFirstAutomatedPipeline.md This Python snippet demonstrates how to set a uniform import scale for animation sequences and then import multiple FBX animation files into Unreal Engine. It uses `anim_factory.factory_import_object` to import various character animations (idle, bored, attack, roaring, run, walk) into specified game paths. ```Python anim_factory.ImportUI.AnimSequenceImportData.ImportUniformScale = 0.1; slicer_idle_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_idle.fbx') animation_idle = anim_factory.factory_import_object(slicer_idle_fbx, '/Game/Kaiju/Slicer/Animations') slicer_bored_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_bored.fbx') animation_bored = anim_factory.factory_import_object(slicer_bored_fbx, '/Game/Kaiju/Slicer/Animations') slicer_attack_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_attack.fbx') animation_attack = anim_factory.factory_import_object(slicer_attack_fbx, '/Game/Kaiju/Slicer/Animations') slicer_roaring_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_roaring.fbx') animation_roaring = anim_factory.factory_import_object(slicer_roaring_fbx, '/Game/Kaiju/Slicer/Animations') slicer_run_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_run.fbx') animation_run = anim_factory.factory_import_object(slicer_run_fbx, '/Game/Kaiju/Slicer/Animations') slicer_walk_fbx = os.path.join(kaiju_assets_dir, 'Animations/slicer_walk.fbx') animation_walk = anim_factory.factory_import_object(slicer_walk_fbx, '/Game/Kaiju/Slicer/Animations') ``` -------------------------------- ### Perform Multi Line Trace in Unreal Engine Python Source: https://github.com/20tab/unrealenginepython/blob/master/docs/uobject_API.md Performs a multi line trace by channel from a start to an end point, returning all hits. ```python [hit0, hit1, ...] = uobject.line_trace_multi_by_channel(start, end, channel) ``` -------------------------------- ### Create Material Instance Directly (Python) Source: https://github.com/20tab/unrealenginepython/blob/master/docs/Material_API.md Demonstrates how to directly create a `MaterialInstanceConstant` in Unreal Engine using Python, setting its name, parent material, and saving it. ```python from unreal_engine.classes import MaterialInstanceConstant material_instance = MaterialInstanceConstant() material_instance.set_name('New Funny Material Instance') material_instance.set_material_parent(new_material) material_instance.save_package('/Game/Materials/instanced') ```