Spawning Multiple Actors

Hey all.

I have a question about the best way to spawn multiple actors.

In my project, I currently have a class called BalloonSpawner which is placed into my world 100 times. When the game runs, there’s a 10% chance of a bad balloon spawning over a good balloon. The respective classes are ‘GoodBalloon’ and ‘BadBalloon’.

In the BalloonSpawner class, within the BeginPlay() function, I have the following code that’ll determine the chances of a Good balloon over a bad balloon

void ABalloonSpawner::BeginPlay()
{
	Super::BeginPlay();

	const float rand = FMath::RandRange(1, 100);
	UE_LOGFMT(LogTemp, Log, "RandRange is {0}", rand);

	if(rand >= 10)
	{
		m_goodBalloon = GetWorld()->SpawnActor<AGoodBalloon>(m_goodBalloonClass);
		m_goodBalloon->AttachToComponent(m_boxComponent, FAttachmentTransformRules::KeepRelativeTransform);
		m_goodBalloon->SetOwner(this);
		m_numOfGoodBalloons++;
	}
	else
	{
		m_badBalloon = GetWorld()->SpawnActor<ABadBalloon>(m_badBalloonClass);
		m_badBalloon->AttachToComponent(m_boxComponent, FAttachmentTransformRules::KeepRelativeTransform);
		m_badBalloon->SetOwner(this);
		m_numOfBadBalloons++;
	}
	
	UE_LOGFMT(LogTemp, Log, "Number of Good Balloons Spawned: {0}", m_numOfGoodBalloons);
	UE_LOGFMT(LogTemp, Log, "Number of Bad Balloons Spawned: {0}", m_numOfGoodBalloons);
	
}

This is the header of where the classes are declared

	UPROPERTY(EditDefaultsOnly)
	TSubclassOf<AGoodBalloon> m_goodBalloonClass;

	UPROPERTY(EditDefaultsOnly)
	TSubclassOf<ABadBalloon> m_badBalloonClass;

	UPROPERTY(EditDefaultsOnly)
	UBoxComponent* m_boxComponent;
	
	UPROPERTY()
	AGoodBalloon* m_goodBalloon;

	UPROPERTY()
	ABadBalloon* m_badBalloon;

When the game starts, every works as expected (even though it’s probably high inefficient). My issue is, if I am looking to show the number of Good and Bad balloons on the players HUD, the number always returns 1 as it’s creating a new instance each time, therefore it doesn’t show the correct amount.

Now, I’m wondering if the way I’m spawning the actors is a trash way of doing it. I was looking into storing the value within the Players Controller, but from my perspective, it doesn’t make sense. I’d ideally like the BalloonSpawner to manage everything to do with the balloons within the level. I’m a bit stuck on what the best approach here would be… here’s a few thoughts I had

  • Create a function within the spawner to handle the counts of the balloons and use that to display to the players HUD
  • Look at creating a better spawner in a more efficient way (need to carry out some investigation)
  • Use a smart pointer to keep track of all the instances within the level
  • Bite the bullet and store the counts in another class (I.E; player controller, or the player class itself)

Other than that, I am a bit lost…

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms