본문 바로가기
AI Image

Unreal에서 Python Script로 OBJ Import하기

by 도승이 2024. 5. 20.

세줄 요약 (gpt4o)
Unreal Engine에서 Python 스크립트를 사용해 OBJ 파일을 임포트하는 방법을 다룹니다. 세 가지 방법을 소개하며, 첫 번째는 AssetImportTask를 사용하는 방법, 두 번째는 InterchangeManager를 이용한 방법, 세 번째는 OBJ 파일을 FBX로 변환해 임포트하는 방법입니다. 각 방법의 장단점을 설명하며, 코드 예제도 포함되어 있습니다.

사용환경

UnrealEngine 5.3
VisualStudio 2022

 

언리얼 엔진에서 스크립트를 이용하여 OBJ 포맷의 파일을 임포트해보자

 

먼저 블루프린트에 Python 스크립트실행 코드부분을 넣어준다.
(디버그를 용이하게 하기위해 버튼을 눌렀을때 파이썬코드가 실행되게끔 해두었다)

필자의 경우, 그냥 파이썬 Path를 ~~~*.py 까지 넣어주었다. 해당 이미지는 EditorUtilityWidget 의 Graph 부분이다.

 

방법 1. OBJ파일을 기존의 언리얼 파이썬 코드(AssetImportTask)를 사용하여 임포트한다

 (UE Python doc 참고)

https://docs.unrealengine.com/5.1/en-US/PythonAPI/class/AssetImportTask.html#unreal.AssetImportTask.options

 

unreal.AssetImportTask — Unreal Python 5.1 (Experimental) documentation

Get the list of imported objects. Note that if the import was asynchronous, this will block until the results are ready. To test whether asynchronous results are ready or not, use IsAsyncImportComplete(). Return type: Array[Object]

docs.unrealengine.com

 

 

import unreal
import os

# Debug
print('Hello from Unreal!')

# 현재 열려 있는 Content Browser의 경로 가져오기
content_browser_path = unreal.EditorUtilityLibrary.get_current_content_browser_path()

print("DEBUG!!!! ", content_browser_path)
# 폴더 내부의 파일 목록 가져오기
files = os.listdir("D:/24_AI/StabilityMatrix-win-x64/Data/Packages/ComfyUI/output/TEST")
# OBJ 파일 찾기
obj_file = None
for file in files:
    if file.endswith('.obj'):
        obj_file = os.path.join("D:/24_AI/StabilityMatrix-win-x64/Data/Packages/ComfyUI/output/TEST", file)
        break

if obj_file:
    # OBJ 파일 가져오기
    import_task = unreal.AssetImportTask()
    import_task.set_editor_property("filename", obj_file)
    import_task.set_editor_property("destination_path", content_browser_path)
    import_task.set_editor_property("automated", True)
    import_task.set_editor_property("save", True)

    import_task.get_objects()

    # 가져온 객체의 경로 출력
    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
    asset = asset_tools.import_asset_tasks([import_task])

    if asset:
        print("Imported asset:", asset.get_full_name())
    else:
        print("Failed to import asset.")
else:
    print("OBJ 파일을 찾을 수 없습니다.")

 

장점 1. python api 페이지를 보며 작업할 수 있다.

단점
- Api 페이지가 불친절하다 (링크를 타고들어가면 세부사항이 보이지않음)

- Import 옵션의 부재 ( 1/100 size로 임포트된다 ,   1m가 -> 1cm단위로 들어온다  , 축이 달라진다.)

 

방법 2. OBJ파일을 5.1이후에 나온 InterchangeManager를 사용하여 임포트한다.

https://forums.unrealengine.com/t/python-or-blueprint-example-for-importing-obj-file-in-ue5-1-interchange-import-pipeline/714987/7

 

Python or Blueprint example for importing obj file in UE5.1, Interchange Import Pipeline

Okay, so we are diving one level deeper in interchange. With interchange you can hook between translation of file and creation of asset, as well as post asset creation etc. So we are going to create a custom pipeline that will modify some of the informatio

forums.unrealengine.com

 

import unreal
import os
obj_path = "D:/24_AI/StabilityMatrix-win-x64/Data/Packages/ComfyUI/output/TEST"
content_browser_path = unreal.EditorUtilityLibrary.get_current_content_browser_path()


files = os.listdir(obj_path)
obj_file = None

for file in files:
    if file.endswith('.obj'):
        obj_file = os.path.join(obj_path, file)
        break
source_data = unreal.InterchangeManager.create_source_data(obj_file)

import_asset_parameters = unreal.ImportAssetParameters()
import_asset_parameters.is_automated = True

eas = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
pipeline = eas.load_asset("/Interchange/Pipelines/CustomLSDAssetsPipeline")
eas.save_loaded_asset(pipeline)
#import_asset_parameters.override_pipelines.append(eas.load_asset("/Interchange/Pipelines/CustomLSDAssetsPipeline"))
#import_asset_parameters.override_pipelines.append(eas.load_asset("/Game/DemoInterchange/DemoCustomChanges"))

ic_mng = unreal.InterchangeManager.get_interchange_manager_scripted()
ic_mng.import_asset("/game/interchange/obj/",source_data,import_asset_parameters)
eas.save_loaded_asset(pipeline)

 

 

장점 : Interchanger 의 pipeline 에셋을 수정하여 임포트옵션을 여러가지 편집 가능하다.

Engine-Plugins-Interchange Framework Content-Pipelines 폴더에 있다.
DefaultAssetsPipeline 을 복사해서 커스텀하게 설정해주고, (이름을 CustomLSD 라고 지어보았다)


eas = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
pipeline = eas.load_asset("/Interchange/Pipelines/CustomLSDAssetsPipeline")
eas.save_loaded_asset(pipeline)

해당 코드로 파이프라인을 설정하여 에셋을 세이브해주면 된다.


방법 3. OBJ파일을 FBX로 변환하여서 임포트한다.

장점

다른 프로그램에서 fbx파일을 편집하기 용이하다.

fbx파일의 이점을 활용할 수 있다. (애니메이션이나 텍스쳐 등 여러 데이터가 들어있다.)

 

 

'AI Image' 카테고리의 다른 글

캐릭터 시트 만들기 (ComfyUI)  (1) 2024.05.22
Photoshop X ComfyUI  (0) 2024.05.21
Perplexity AI  (0) 2024.05.09
ComfyUI X UnrealEngine - ComfyTexture 개발 일지 (1)  (0) 2024.05.07
Meta llama-3 소개 및 다운로드 및 설치  (0) 2024.04.30

댓글