How to make percentage based spawning system

If you are willing to write about 30-40 lines of code you can get a blueprint node for this :
1 - From the editor’s Tools menu choose “New C++ class”
2 - In the all classes tab look for BluePrintFunctionLibrary and select it.
3 - Press next and then create class. Two files will be created in the directory shown in the last step before pressing create class
4 - Open the file that ends with “.h”
5 - copy the code below and paste under the line with the words “GENERATED_BODY”
6 - Compile your project

public:
	UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Random")
	static TSubclassOf<AActor> GetRandomActor(const TMap<TSubclassOf<AActor>, float>& ActorMap)
	{
		const float RandomValue  = FMath::FRandRange(0.f, 100.f);
		float CumulativePercent  = 0.f;
#if WITH_EDITOR
		TSubclassOf<AActor> SelectedActor = nullptr;
		for (const auto& Element : ActorMap)
		{
			checkf(Element.Value >= 0 , TEXT("Percentages must be positive when using Get Random Actor node!"));
			CumulativePercent += Element.Value;
			if (RandomValue <= CumulativePercent
				&& SelectedActor == nullptr)
			{
				SelectedActor = Element.Key;
			}
		}
		checkf(FMath::IsNearlyEqual(CumulativePercent, 100.f, UE_KINDA_SMALL_NUMBER), TEXT("Sum of the percentages must be 100 when using Get Random Actor node!"));
		return SelectedActor;
#else
		for (const auto& Element : ActorMap)
		{
			CumulativePercent += Element.Value;
			if (RandomValue <= CumulativePercent)
			{
				return Element.Key;
			}
		}
		return ActorMap.Array().Last().Key;
#endif
	}

This will give you a node like this:

Key is the actor you want to spawn and value is the spawn chance.
If you give any negative value or your percentages don’t add up to 100 and you are playing with editor this will crash your game and you will see why it crashed (either negative value or the sum) in the crash log. Outside of editor builds you just get the last actor in the map if you don’t give it correct values. An empty map will crash your game (or maybe it doesn’t f^^; check this one yourself).

Sorry if you wanted a BP exclusive answer >.<;

1 Like