Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to store a highest variable and add to leaderboard stat?

So, I've got a game where you fling yourself off a ramp. I've got some code to detect magnitude and put it into a leaderstat, but I want to find the highest magnitude before death, and then add that to the leaderstat. Sort of like a currency system. Below is the code for the magnitude stat that I currently have.

local Players = game:GetService("Players")

local point = workspace.Wedge

local function find_distance(speed: number, character: Model)
	local player = Players:GetPlayerFromCharacter(character)
	local root_part = character:WaitForChild("HumanoidRootPart")

	local leaderstats = player:WaitForChild("leaderstats")
	local magnitude = leaderstats.Magnitude

	magnitude.Value = (root_part.Position - point.Position).Magnitude
end

local function character_added(character)
	print(character.ClassName)
	local humanoid = character:WaitForChild("Humanoid")

	humanoid.Running:Connect(function(speed)
		find_distance(speed, character)
	end)
end

local function player_added(player: Player)
	player.CharacterAdded:Connect(character_added)

	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player 

	local magnitude = Instance.new("IntValue")
	magnitude.Name = "Magnitude"
	magnitude.Parent = leaderstats
end

Players.PlayerAdded:Connect(player_added)

3 comments

0

Record whatever the last known highest magnitude was, then do not update the IntValue unless the calculated magnitude exceeded the record. Update the record as you update the IntValue.

0

That does sound like it could work, but im just not sure how to do that.

0

Actually, your IntValue already acts as the record.

2 answers

I don't have a perfect match but..


local magnitudes = {}
local best = nil
local score = 0

for i,v in pairs(magnitudes) do 
	if v.Value > score then
		score = v.Value
		best = v
	end
end

print(best.."  Had the largest value, with a magnitude of "..score.." !"

You'd need to store all the magnitude in a table and then run this with "score" being the largest magnitude!

1 comment

0

Storing magnitudes over time is super inefficient. You can also simplify that logic to: math.max(unpack(magnitudes))

local magnitude_record = leaderstats.Magnitude
local magnitude = player:DistanceFromCharacter(ramp)

if magnitude_record.Value < magnitude then
    magnitude_record.Value = magnitude
end

1 comment

0

This just completely made the magnitude leaderstat vanish

This discussion is preserved as it was. New answers, comments, and votes are closed.