What is the best way to assign a static to an Actor?

I am new to C++ programming in UE4 and am trying to procedurally assign a Static mesh object to a newly generated Pawn(Actor). I am using the “SetStaticMesh” function in the constructor however nothing seems to be happening. What is the proper method for doing this?

My Code:

AMyPawn::AMyPawn()
{
   ...
   USceneComponent* OurVisibleComponent;
   RootComponent = CreateDefaultSubobject(TEXT("RootComponent"));
   OurVisibleComponent = CreateDefaultSubobject(TEXT("Our Visible Component"));
   OurVisibleComponent->AttachTo(RootComponent);
   UStaticMeshComponent *myStaticMeshComponent = (UStaticMeshComponent *)OurVisibleComponent;
   static ConstructorHelpers::FObjectFinder    StaticMeshOb_AW2(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Torus'"));
   UStaticMesh *myStaticMesh = StaticMeshOb_AW2.Object;
   myStaticMeshComponent->SetStaticMesh(myStaticMesh);

   ...
}

Thanks for your help!

Hi RudeyPunk,

Your setup is close to correct, but I believe the main issue you are running into is one of scope. A variable that is declared inside a function will only exist inside that function. In this case you are declaring several component variables in your constructor, and those variables will cease to exist once the constructor finishes executing. What you actually want to have is something like the following:

In the header file for your class:

UPROPERTY()
USceneComponent* OurVisibleComponent;

UPROPERTY()
UStaticMeshComponent* MyStaticMeshComponent;

And in the source file for your class:

AMyPawn::AMyPawn()
{
 	OurVisibleComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Our Visible Component"));
	RootComponent = OurVisibleComponent;

	MyStaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("My Static Mesh Component"));
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshOb_AW2(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Torus'"));
	UStaticMesh* MyStaticMesh = StaticMeshOb_AW2.Object;
	MyStaticMeshComponent->SetStaticMesh(MyStaticMesh);
	MyStaticMeshComponent->AttachTo(OurVisibleComponent);
}

This solves the scope problem by declaring the components as members of the class, so that they will exist as long as an object of the class exists.

Unless you are doing something specific with OurVisibleComponent, you don’t even need to have that. You could set MyStaticMeshComponent as the root component and it would work fine. Also, even though each new Actor class does have a default root component, if you are adding your own components to the class it is usually a good idea to set the RootComponent equal to whatever component you want as the root in the hierarchy of your class.

Woohoo !
I should have guessed.
Thanks for pointing this out!
This fixed solved the problem quickly!
Cheers