Instanced Static Mesh

Hi all I’m playing around with instanced static meshes and now when I initialize and create everything in constructor and create my instanced static mesh with call to “CreateDefaultSubobject<>” everything works as intended the instance is created and I can add instances of static meshes, I would like to move this code away from constructor and execute it in BeginPlay() method however I encountered a problem the “CreateDefaultSubobject<>” can be called only in constructor so I’m using “NewObject<>” to create InstancedStaticMeshComponent the instance is created successfully I can set a static mesh on it, however when I call “AddInstance” passing in transform the exception is thrown I’ve investigated a bit and it seams that it is thrown because the OwnerActor is nullptr here a code

Code From Constructor this works fine

instancedMeshesComponent = CreateDefaultSubobject<UMyInstancedStaticMeshComponent>(*tempName);
instancedMeshesComponent->AttachTo(RootComponent);

instancedMeshesComponent->SetStaticMesh(MeshType); // MeshType is set to cube

FTransform transform;
transform.SetLocation(FVector(0, 0, 0));

instancedMeshesComponent->AddInstance(transform);

Code from BeginPlay this doesnt work the exception is thrown at “AddInstance(transform)” line also I’m not sure what I should pass in as the “Outer” argument so I just pass in current level but I’ve tried to pass in “World” and also the StaticClass() of the object where instancedStaticMesh is declared no changes

    instancedMeshesComponent = NewObject<UMyInstancedStaticMeshComponent>(GetWorld()->GetCurrentLevel(),*tempName);
    instancedMeshesComponent->AttachTo(RootComponent);
    
    instancedMeshesComponent->SetStaticMesh(MeshType); // MeshType is set to cube
    
    FTransform transform;
    transform.SetLocation(FVector(0, 0, 0));
    
    instancedMeshesComponent->AddInstance(transform); // exception is thrown at this line

Right passing in “this” pointer as Outer argument solved a half of the problem now it doesn’t throw exception but the mesh is not rendered

I was having the same issue. Looks like you need to add

instancedMeshesComponent->RegisterComponentWithWorld(GetWorld());

to get it to appear