Spawn Sphere as child in C++

Hi,

I am trying to spawn a sphere from my C++ actor. I want the sphere to be in front of my actor and to stay attached to it (stay in front if the actor itself moves).

I tried to spawn a StaticMeshComponent and attaching the sphere mesh in “Engine/BasicShapes/Sphere”, but Unreal won’t let me spawn it because it is not an actor.

UStaticMeshComponent *sphere = GetWorld()->SpawnActor<UStaticMeshComponent>(loc, rot, params);

gives the warning message:

LogSpawn:Warning: SpawnActor failed
because StaticMeshComponent is not an
actor class

What is the correct way to spawn StaticMeshComponents then?
Thank you!

Hey,

A sphere is indeed not an actor class, I believe it comes under a primitive component. You can do one of two things.

Instead of using spawnActor, add a static mesh component. Rama has written a wiki post on how to do this, it also includes how to parents it. If you want to move in front of actor, you should just be able to call ->SetRelativePosition() as well during the setup.
https://wiki.unrealengine.com/Actor_Components,Making_Native%26_Deferred_Attached_to_Socket

Otherwise, if you need to use spawn, just place the sphere in a actor blueprint, and then spawn that instead.

Hi,
Thanks for linking the tutorial, it pointed me in the right direction. However, I want to spawn the spheres outside of the constructor, so this method does not work. A little google search pointed me to NewNamedObject, which I am now using. This works fine, but somehow the spheres have a strange hirarchy. I am spawning 5 of them in a loop, using

	UStaticMeshComponent *sphere = NewNamedObject<UStaticMeshComponent>(this, FName(*name_f));

	sphere->SetStaticMesh(point_mesh);
	sphere->SetMaterial(0,marker_material);
	sphere->RelativeLocation = loc;
	sphere->RelativeRotation = rot;

But in the Editor the first Sphere is a child of my actor, while the other 4 are children of the first sphere. Why is that?

I fixed this by adding a dummy component to my actor. All the spheres are then created as children of that dummy. Apparently all actors need to have a root component, is that right?