Creating a building that spawns units

For this recipe, we will create a building that spawns units at a fixed time interval at a particular location.

How to do it...

  1. Create a new Actor subclass in the editor, as always, and then add the following implementation to the class:
    UPROPERTY()
    UStaticMeshComponent* BuildingMesh;
    UPROPERTY()
    UParticleSystemComponent* SpawnPoint;
    
    UPROPERTY()
    UClass* UnitToSpawn;
    
    UPROPERTY()
    float SpawnInterval;
    
    UFUNCTION()
    void SpawnUnit();
    
    UFUNCTION()
    void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
    
    UPROPERTY()
    FTimerHandle SpawnTimerHandle;
  2. Add the following to the constructor:
    BuildingMesh = CreateDefaultSubobject<UStaticMeshComponent>("BuildingMesh"); SpawnPoint = CreateDefaultSubobject<UParticleSystemComponent>("SpawnPoint"); ...

Get Unreal Engine 4 Scripting with C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.