Search code examples
c++unreal-engine4

How to get components of UStaticMesh Array?


Hej,

In the below code, I'm trying to get the components of UStaticMesh Array, but i'm getting an error as follows.

Error 1 error C2338: 'T' template parameter to GetComponents must be derived from ActorComponent

In .h file

UPROPERTY()
        TArray<UStaticMeshComponent*> StaticMeshComponent;
UPROPERTY()
        TArray<UStaticMesh*> StaticMesh;

In .CPP file

StaticMeshComponent = TArray<UStaticMeshComponent*>();
StaticMeshtemp = TArray<UStaticMesh*>();

for (int32 i = 0; i < 3; i++)
{
    GetComponents<UStaticMeshComponent>(StaticMeshComponent);
    StaticMeshComponent[i] = CreateDefaultSubobject<UStaticMeshComponent>(temp);

    GetComponents<UStaticMesh>(StaticMesh);
    StaticMesh[i] = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *SMPath));

Is there any another function or method to get the components of UStaticMesh Array ???


Solution

  • I believe this is not necesarry:

    StaticMeshComponent = TArray<UStaticMeshComponent*>();
    StaticMeshtemp = TArray<UStaticMesh*>();
    

    Both arrays are initialized before running constructor.

    Problem:

    This code is OK:

     GetComponents<UStaticMeshComponent>(StaticMeshComponent);
     StaticMeshComponent[i] = CreateDefaultSubobject<UStaticMeshComponent>(temp);
    

    StaticMeshComponent is derived from ActorComponent UE Doc.

    And this is wrong:

     GetComponents<UStaticMesh>(StaticMesh);
    

    Because as you can find in UE Doc StaticMesh, StaticMesh is not derived from ActorComponent.

    Solution:

    All you need is call SetStaticMesh function on each StaticMeshComponent that you created via CreateDefaultSubobject<...>.