Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include "CoreMinimal.h"
- #include "Kismet/BlueprintFunctionLibrary.h"
- #include "Runtime/Engine/Classes/GameFramework/Actor.h"
- #include "Kismet/KismetMathLibrary.h"
- #include "LootBox.generated.h"
- // Custom struct that ties an object class to an integer to determine drop rate
- USTRUCT(BlueprintType)
- struct FLoot_Box
- {
- GENERATED_USTRUCT_BODY()
- public:
- UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Nebula Structs")
- TSubclassOf <AActor> Item_Class;
- UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Nebula Structs", meta = (ClampMin = "0", ClampMax = "100", UIMin = "0", UIMax = "100"))
- int32 Drop_Rate;
- };
- UCLASS()
- class CODE_TEST_API ULootBox : public UBlueprintFunctionLibrary
- {
- GENERATED_BODY()
- public:
- /* Input "Loot Box" struct array and their respective "drop rate" ( 50 = 50% chance of being selected),
- output will be the randomly selected class. The boolean output is for error handling to ensure the total "drop rate" = 100
- Node will not function unless the total is exactly 100, negative values will be treated as their positive counterparts */
- UFUNCTION(BlueprintCallable, meta = (Category = "Nebula Nodes", Keywords = "Loot, Drop, Random, Loot Box, Chance"))
- static void Random_Drop_Rate(TArray <FLoot_Box> Loot_Classes, TSubclassOf <AActor> &Drop_Item, bool &Drop_Rate_Equal_100);
- };
- ------------------------------------------------------------------------------------------------------------------------------
- // Fill out your copyright notice in the Description page of Project Settings.
- #include "LootBox.h"
- void ULootBox::Random_Drop_Rate(TArray <FLoot_Box> Loot_Classes, TSubclassOf <AActor> &Drop_Item, bool &Drop_Rate_Equal_100)
- {
- // Declare temporary integer array for storing all "Drop Rates"
- TArray <int32> DropRateArray;
- int32 EqualTo100 = 0;
- // Add input array drop rates to temporary array while summing the values to create a range "max" for each Loot Item
- for (int x = 0; x < Loot_Classes.Num(); ++x)
- {
- if (x == 0)
- {
- DropRateArray.Add(FMath::Abs(Loot_Classes[x].Drop_Rate));
- }
- else
- {
- DropRateArray.Add(FMath::Abs(Loot_Classes[x].Drop_Rate) + (DropRateArray[x-1]));
- }
- }
- // Ensure all "Drop Rates" sum to EXACTLY 100
- if (DropRateArray.Last() == 100)
- {
- // Generate a random number
- int32 DropIndex = UKismetMathLibrary::RandomIntegerInRange(1, 100);
- // Start with the lowest range "max value" and keep moving up until random int <= max of range
- for (int x = 0; x < DropRateArray.Num(); ++x)
- {
- if (DropIndex <= DropRateArray[x])
- {
- Drop_Item = Loot_Classes[x].Item_Class;
- break;
- }
- else
- ;
- }
- Drop_Rate_Equal_100 = true;
- }
- // If drop rates do NOT sum to exactly 100 return a false boolean and a null drop item
- else
- {
- Drop_Item = nullptr;
- Drop_Rate_Equal_100 = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment