Search code examples
c++unreal-engine4

How to spawn 10 spheres in C++


Say I have chosen First Person template in UE IDE, and I am expected to create 10 spheres at distance of 1500 units. Also when one shoots some sphere then the sphere disappears. How do I create spheres in C++?


Solution

  • You would normally use the SpawnActor method in the UWorld class. You can find more info about the method here, but essentially you would get a reference to the world, call SpawnActor using that UWorld reference while passing in four parameters: the actor you want to spawn, which is usually of type TSubclassOf<AActor> where AActor can be any subclass of type AActor, the location of the actor to be spawned, which is of type FVector, the rotation of the actor to be spawned, which is of type FRotator, and some additional information of the actor to be spawned, which is of type FActorSpawnParameters. Here's an example of the function being called. First the header file,

    // header file (.h)
    UPROPERTY(EditDefaultsOnly, Category = "Actor To Be Spawned")
    TSubclassOf<AActor> ActorToBeSpawned;
    

    Note that this property will be set in blueprints.

    Then, somewhere in the cpp class,

    // cpp class (.cpp)
    FActorSpawnParameters SpawnParams;
    GetWorld()->SpawnActor<AActor>(ActorToBeSpawned, FVector(300, 300, 300), FRotator::ZeroRotator, SpawnParams);
    

    Note that the last parameter is optional, but you can always set specific properties in your FActorSpawnParameters. For a list of all those specific properties, you can find them here. Also, the second parameter, which is the location of the actor to be spawned is currently hardcoded in this example, so you can make it anything. Each number in the FVector passed in represents the x, y, and z coordinates respectfully. Lastly, the third parameter is currently a FRotator object of zero degrees on each axis so the actor to be spawned will use its default specified rotation.

    With that said, you should be able to incorporate this logic in your custom logic so that you can achieve your goal of spawning 10 sphere actors separated by a certain distance.