You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UE4技术问询:如何在C++中获取非C++派生蓝图类的组件?

问题

蓝图类中的StaticMeshComponent
我在Unreal Engine编辑器中创建了一个非C派生的蓝图类,其中添加了多个StaticMeshComponent。请问如何在C类中获取该蓝图类的所有组件?

我的尝试代码如下:
TileGenerater.h

TSubclassOf<TileActor> TileType;

TileGenerater.cpp

AActor* TileActor = TileType.GetDefaultObject();
auto TileComponents = TileActor->GetComponents();

但TileComponents中没有任何元素。我猜测GetComponents仅对已生成到世界中的Actor生效,恳请帮助!

解决方案

你的猜测正确,GetComponents()仅对已在世界中实例化的Actor有效,而GetDefaultObject()获取的是类的默认对象(蓝图编辑器中的"Class Default Object"),蓝图中添加的组件不会被初始化到这个默认对象里。

要获取蓝图类中添加的组件,需要通过**蓝图的类数据(UBlueprint)**访问,具体实现如下:

// 确保TileType指向有效类
if (TileType)
{
    // 将类转换为蓝图对象
    UBlueprint* Blueprint = Cast<UBlueprint>(TileType->ClassGeneratedBy);
    if (Blueprint)
    {
        UClass* GeneratedClass = Blueprint->GeneratedClass;
        if (GeneratedClass)
        {
            // 遍历蓝图生成类中的所有组件属性
            for (TFieldIterator<UComponentProperty> PropIt(GeneratedClass); PropIt; ++PropIt)
            {
                UComponentProperty* ComponentProp = *PropIt;
                // 筛选StaticMeshComponent类型的组件
                if (ComponentProp->PropertyClass->IsChildOf(UStaticMeshComponent::StaticClass()))
                {
                    UE_LOG(LogTemp, Log, TEXT("找到StaticMeshComponent: %s"), *ComponentProp->GetName());
                    // 这里可根据需求处理组件信息
                }
            }
        }
    }
}

如果你的需求是获取实例化后Actor的组件,则需要先在世界中生成Actor实例,再调用GetComponents():

if (TileType && GetWorld())
{
    ATileActor* SpawnedTile = GetWorld()->SpawnActor<ATileActor>(TileType);
    if (SpawnedTile)
    {
        TArray<UActorComponent*> TileComponents = SpawnedTile->GetComponents();
        // 遍历处理所有组件
        for (UActorComponent* Comp : TileComponents)
        {
            if (UStaticMeshComponent* StaticMeshComp = Cast<UStaticMeshComponent>(Comp))
            {
                // 对StaticMeshComponent执行操作
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者user117474

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:01:53