[ue5] python rename 依存関係のあるファイルをチェックアウトしてからリネームする下調べ

rename_asset(asset, newName) 色々あるが基本はこれでいい。むしろこれしか動かず。

editor_util = unreal.EditorUtilityLibrary()
# 新しい名前
newName = newName
                
# リネームしたいアセット
asset = unreal.load_asset(package_name)
                
# rename実行
editor_util.rename_asset(asset, newName)

複数ファイルに対応する。

    def rename_endZ_remove_loop(self):
        editorAssetLib = unreal.EditorAssetLibrary()
        editor_util = unreal.EditorUtilityLibrary()
        #editorStaticMeshLib = unreal.EditorStaticMeshLibrary()
        MaterialEditingLibrary = unreal.MaterialEditingLibrary()
        asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()

        #import unreal.AssetRegistry
        #AssetRegistry=unreal.AssetRegistry()
        
        EnvName=unreal.Name.cast("/Game/Effects")

        #EnvName=unreal.Name.cast(readDirPath)
        EnvArr=unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)
        
        #EnvArr = asset_registry.get_assets()
        #EnvArr =self.SelectedAssets
        
        unreal.log_warning("main_way_start2 040  unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)")
        unreal.log_warning("main_way_start2 041  get_assets_by_path() EnvArr len= "+str(len(EnvArr)))

        NGlist=[]       
        checkout_Arr=[] 
        checkout_Arr_Str=""
        rename_data_Arr=[]
        total_frames = len(EnvArr)
        text_label = "Rename Execution!"
        with unreal.ScopedSlowTask(total_frames, text_label) as slow_task:
            slow_task.make_dialog(True)               # まだダイアログが表示されていない場合は表示します
            for i in range(total_frames):
                if slow_task.should_cancel():# ユーザーが UI の [Cancel] を押した場合は True
                    break
                slow_task.enter_progress_frame(1)# 1 フレーム次に進めます。
                

                AssetData=EnvArr[i]
                print("AssetData= "+str(AssetData))
                package_name=str(AssetData.package_name)
                print("package_name= "+str(package_name))
                package_name_Arr=package_name.split("/")
                package_name_Arr_len=len(package_name_Arr)
                print("package_name_Arr_len= "+str(package_name_Arr_len))
                assetName=package_name_Arr[package_name_Arr_len-1]
                print("assetName= "+str(assetName))
                assetNameStr=str(assetName)+"."
                
                # 新しい名前
                newName=assetNameStr.replace("Z.","")
                
                # リネームしたいアセット
                asset = unreal.load_asset(package_name)
                
                # 新しいパッケージパス
                new_package_path = package_name+"."
                new_package_path=new_package_path.replace("Z.","")
                
                editor_util.rename_asset(asset, newName)
                
                # リネームデータを作成
                #rename_data = unreal.AssetRenameData(asset, new_package_path, new_name)
                #unreal.EditorUtilityLibrary.rename_asset(rename_data)
                #rename_data_Arr.append(rename_data)
        
        #rename_assets(rename_data_Arr)

依存関係のあるファイルをチェックアウトしてからリネーム

# -*- coding: utf-8 -*- 
import unreal
import sys
import os
import re
import codecs
import os
import datetime
unreal.log("--------------py--start000-----------------")
unreal.log("    ")

class RefferenceCounter():

    def mainWay(self):
        
        self.AssetRegistryLoaded=False
        #----------------------------------------------------------
        self.tickhandle = None
        self.tickhandle = unreal.register_slate_pre_tick_callback(self.testRegistry)
        print("tickhandle="+str(self.tickhandle))

        
    def testRegistry(self,deltaTime):
        unreal.log_warning("ticking...mainWay")
        asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
        if asset_registry.is_loading_assets():
            unreal.log_warning("still loading...mainWay")
        else:
            unreal.log_warning("ready!.....mainWay")
            if(self.AssetRegistryLoaded==False):
                self.AssetRegistryLoaded=True
                self.textLoad2()
                #self.textLoad()
                
            unreal.unregister_slate_pre_tick_callback(self.tickhandle)
            unreal.unregister_slate_pre_tick_callback(self.tickhandle)

    def getProject_SavedDir(self):
        project_saved_dir=unreal.Paths.project_saved_dir()
        print("project_saved_dir= "+project_saved_dir)
        HD_project_saved_dir=os.path.abspath(project_saved_dir)
        print("HD_project_saved_dir= "+HD_project_saved_dir)
        HD_project_saved_dir_slash=HD_project_saved_dir.replace('\\', '/')
        print("HD_project_saved_dir_slash= "+HD_project_saved_dir_slash)
        return HD_project_saved_dir_slash

    def get_project_dir(self):
        project_dir=unreal.Paths.project_dir()
        print("project_dir= "+project_dir)
        HD_project_dir=os.path.abspath(project_dir)
        print("HD_project_dir= "+HD_project_dir)
        HD_project_dir_slash=HD_project_dir.replace('\\', '/')
        print("HD_project_dir_slash= "+HD_project_dir_slash)
        return HD_project_dir_slash

    def textLoad2(self):
        import codecs
        readPath=self.getProject_SavedDir()+'/RefferenceCounter/SelectedAsset.txt'
        print("readPath= "+readPath)
        fin = codecs.open(readPath, 'r', 'utf_8')
        
        SelectedAssetArr=[]
        for line in fin:
            line=line.replace(" ","")#Space
            line=line.replace(" ","")#TAB
            line=line.replace("\r","")
            line=line.replace("\n","")
            if(line==""):
                pass
            else:
                SelectedAssetArr.append(line)
        #txtData=fin.read()
        print("SelectedAssetArr= "+str(SelectedAssetArr))
        #rejectLines=txtData
        #print("SelectedAssets= "+SelectedAssets)
        self.SelectedAssets=SelectedAssetArr
        self.main_way_start2()

     
    def main_way_start2(self):

        editorAssetLib = unreal.EditorAssetLibrary()
        editor_util = unreal.EditorUtilityLibrary()
        #editorStaticMeshLib = unreal.EditorStaticMeshLibrary()
        MaterialEditingLibrary = unreal.MaterialEditingLibrary()
        asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()

        #import unreal.AssetRegistry
        #AssetRegistry=unreal.AssetRegistry()
        
        EnvName=unreal.Name.cast("/Game/Materials")
        EnvName_Str=editor_util.get_current_content_browser_path()
        EnvName=unreal.Name.cast(EnvName_Str)
        
        #EnvName=unreal.Name.cast(readDirPath)
        EnvArr=unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)
        

        
        unreal.log_warning("main_way_start2 040  unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)")
        unreal.log_warning("main_way_start2 041  get_assets_by_path() EnvArr len= "+str(len(EnvArr)))

        NGlist=[]       
        checkout_Arr=[] 
        checkout_Arr_Str=""
        total_frames = len(EnvArr)
        text_label = "reference And Dependency Checking!"
        with unreal.ScopedSlowTask(total_frames, text_label) as slow_task:
            slow_task.make_dialog(True)               # まだダイアログが表示されていない場合は表示します
            for i in range(total_frames):
                if slow_task.should_cancel():# ユーザーが UI の [Cancel] を押した場合は True
                    break
                slow_task.enter_progress_frame(1)# 1 フレーム次に進めます。
                

                #package_name=EnvArr[i]
                AssetData=EnvArr[i]
                print("AssetData= "+str(AssetData))
                package_name=str(AssetData.package_name)
                print("package_name= "+str(package_name))
                package_name_Arr=package_name.split("/")
                package_name_Arr_len=len(package_name_Arr)
                print("package_name_Arr_len= "+str(package_name_Arr_len))
                assetName=package_name_Arr[package_name_Arr_len-1]
                print("assetName= "+str(assetName))
                
                
                dependency_options=unreal.AssetRegistryDependencyOptions(include_soft_package_references=True, include_hard_package_references=True, include_searchable_names=False, include_soft_management_references=False, include_hard_management_references=False)
                #
                asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
                dependencies=unreal.AssetRegistry.get_dependencies(asset_registry,package_name, dependency_options)
                referencers=unreal.AssetRegistry.get_referencers(asset_registry,package_name, dependency_options)
                
                dependencies_len=len(dependencies)
                referencers_len=len(referencers)
                print("----------------referencers_len= "+str(referencers_len)+"-------------------")

                dependencies_str=self.array_to_str(dependencies)
                referencers_str=self.array_to_str(referencers)
                all_ref_dependencys_str=dependencies_str+"|"+referencers_str
                all_ref_dependencys_len=referencers_len+dependencies_len
                #A=assetName+","+assetPath
                A=assetName+","+str(referencers_len)+","+referencers_str+","+str(dependencies_len)+","+dependencies_str+","
                A=A+str(all_ref_dependencys_len)+","+all_ref_dependencys_str
                
                checkout_Arr_Str=checkout_Arr_Str+all_ref_dependencys_str+"|"+package_name+"|"
                #A=A+","+str(package_name)
                #for dep in dependencies:
                #    A=A+","+str(dep)
                NGlist.append(A)
                unreal.log_warning(A)
        
        # チェックアウト
        checkout_Arr=checkout_Arr_Str.split("|")
        for checkout_file_path in checkout_Arr:
            if checkout_file_path=="":
                pass
            else:
                unreal.EditorAssetLibrary.checkout_asset(checkout_file_path)
    
        
        self.rename_endZ_remove_loop(EnvName_Str)     
        
    def rename_endZ_remove_loop(self,EnvName_Str):
        editorAssetLib = unreal.EditorAssetLibrary()
        editor_util = unreal.EditorUtilityLibrary()
        #editorStaticMeshLib = unreal.EditorStaticMeshLibrary()
        MaterialEditingLibrary = unreal.MaterialEditingLibrary()
        asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()

        #import unreal.AssetRegistry
        #AssetRegistry=unreal.AssetRegistry()

        EnvName=unreal.Name.cast(EnvName_Str)
        
        #EnvName=unreal.Name.cast(readDirPath)
        EnvArr=unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)
        
        #EnvArr = asset_registry.get_assets()
        #EnvArr =self.SelectedAssets
        
        unreal.log_warning("main_way_start2 040  unreal.AssetRegistry.get_assets_by_path(asset_registry,EnvName,True,False)")
        unreal.log_warning("main_way_start2 041  get_assets_by_path() EnvArr len= "+str(len(EnvArr)))

        NGlist=[]       
        checkout_Arr=[] 
        checkout_Arr_Str=""
        rename_data_Arr=[]
        total_frames = len(EnvArr)
        text_label = "Rename Execution!"
        with unreal.ScopedSlowTask(total_frames, text_label) as slow_task:
            slow_task.make_dialog(True)               # まだダイアログが表示されていない場合は表示します
            for i in range(total_frames):
                if slow_task.should_cancel():# ユーザーが UI の [Cancel] を押した場合は True
                    break
                slow_task.enter_progress_frame(1)# 1 フレーム次に進めます。
                

                AssetData=EnvArr[i]
                print("AssetData= "+str(AssetData))
                package_name=str(AssetData.package_name)
                print("package_name= "+str(package_name))
                package_name_Arr=package_name.split("/")
                package_name_Arr_len=len(package_name_Arr)
                print("package_name_Arr_len= "+str(package_name_Arr_len))
                assetName=package_name_Arr[package_name_Arr_len-1]
                print("assetName= "+str(assetName))
                assetNameStr=str(assetName)+"."
                
                # 新しい名前
                newName=assetNameStr.replace("Z.","")
                
                
                # リネームしたいアセット
                asset = unreal.load_asset(package_name)
                
                # 新しいパッケージパス
                new_package_path = package_name+"."
                new_package_path=new_package_path.replace("Z.","")
                
                editor_util.rename_asset(asset, newName)
                
                # リネームデータを作成
                #rename_data = unreal.AssetRenameData(asset, new_package_path, new_name)
                #unreal.EditorUtilityLibrary.rename_asset(rename_data)
                #rename_data_Arr.append(rename_data)
        
        #rename_assets(rename_data_Arr)

Class_Ins=RefferenceCounter()
Class_Ins.mainWay()

CGWORLD.JPさんから引用、「リネームとリダイレクタはある意味密接な関係にある…

KAEditorUtilityBlueprintLibrary.h

#pragma once
 
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "KAEditorUtilityBlueprintLibrary.generated.h"
 
UCLASS()
class KAEDITORUTILITYTEST_API UKAEditorUtilityBlueprintLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
public:
	//RedirectorをFixUpする
	UFUNCTION(BlueprintCallable, Category = "KAEditorUtility")
	static void FixupRedirectors(const TArray<FAssetData>& Assets, bool bCheckoutDialogPrompt);
};

KAEditorUtilityBlueprintLibrary.cpp

#include "KAEditorUtilityBlueprintLibrary.h"
#include "AssetToolsModule.h"
 
void UKAEditorUtilityBlueprintLibrary::FixupRedirectors(const TArray<FAssetData>& Assets, bool bCheckoutDialogPrompt)
{
	FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>(TEXT("AssetTools"));
	//Redirectorの取得
	TArray<UObjectRedirector*> Redirectors;
	for (FAssetData Object : Assets)
	{
		if (UObjectRedirector* Redirector = Cast<UObjectRedirector>(Object.GetAsset()))
		{
			Redirectors.Emplace(Redirector);
		}
	}
 
	if (Redirectors.Num() > 0)
	{
		AssetToolsModule.Get().FixupReferencers(Redirectors, bCheckoutDialogPrompt);
		return true;
	}
	return false;
}

参考URL

https://cgworld.jp/regular/202312-ue5tool-01.html

https://docs.unrealengine.com/5.0/en-US/PythonAPI/class/EditorAssetLibrary.html

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です