Remote Event / Script Help

If the player is number #1 on the leaderboard in the datastore named Board, then allow the pet equipping.

Server Side

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local EquipPetEvent = ReplicatedStorage:WaitForChild("EquipPetEvent")
local RemovePetEvent = ReplicatedStorage:WaitForChild("RemovePetEvent")
local DataStoreService = game:GetService("DataStoreService")
local PlayerDataStore = DataStoreService:GetOrderedDataStore("Board")
local PetCheckerEvent = game.ReplicatedStorage:WaitForChild("DonatorPetChecker")

local function MovePet(player, pet)
	local lastTime = tick()
	local speed = 1.5 -- Adjust speed as needed
	local bobbingAmplitude = 0.5 -- Adjust bobbing amplitude as needed
	local bobbingFrequency = 2 -- Adjust bobbing frequency as needed

	local function onHeartbeat()
		local currentTime = tick()
		local deltaTime = currentTime - lastTime
		lastTime = currentTime

		if player.Character and player.Character:FindFirstChild("HumanoidRootPart") and pet.PrimaryPart then
			local playerPosition = player.Character.HumanoidRootPart.Position
			local offset = Vector3.new(-5, 3, -4)
			local newPosition = playerPosition + offset

			-- Calculate bobbing motion
			local bobbingOffset = Vector3.new(0, math.sin(currentTime * bobbingFrequency) * bobbingAmplitude, 0)
			newPosition = newPosition + bobbingOffset

			-- Interpolate the pet's position towards the new position with delta time
			local currentPos = pet.PrimaryPart.Position
			local newPos = currentPos:Lerp(newPosition, speed * deltaTime)
			pet:SetPrimaryPartCFrame(CFrame.new(newPos))

			-- Calculate the new rotation for the pet
			local lookRotation = CFrame.new(pet.PrimaryPart.Position, playerPosition)
			local initialRotationOffset = CFrame.Angles(0, math.rad(-90), 0)
			lookRotation = lookRotation * initialRotationOffset

			-- Set the pet's rotation directly
			pet:SetPrimaryPartCFrame(lookRotation)
		end
	end

	-- Connect to Heartbeat event
	local connection
	connection = game:GetService("RunService").Heartbeat:Connect(function()
		onHeartbeat()
	end)
	
	-- Disconnect the event when pet is removed or parent changes
	pet.AncestryChanged:Connect(function()
		if not pet:IsDescendantOf(game) then
			connection:Disconnect()
		end
	end)
end


local function RemovePlayerPets(player)
	local playerCharacter = player.Character
	if playerCharacter then
		for _, child in ipairs(playerCharacter:GetChildren()) do
			if child.Name == "DragonCompanion_4" then
				child:Destroy()
			end
		end
	end
end

local function checkDataStoreAndEquipPet(player)
	-- Fetch the highest value from the ordered DataStore
	local success, leaderboard = pcall(function()
		return PlayerDataStore:GetSortedAsync(false, 1) -- Descending order, top player
	end)

	if success then
		local topPlayerEntry = leaderboard:GetCurrentPage()[1] -- Get the top player entry
		if topPlayerEntry then
			local topPlayerId = topPlayerEntry.key -- Get the UserId of the top player
			if topPlayerId == player.UserId then
				-- Player is the top player, allow equipping
				return true
			else
				-- Player is not the top player, prevent equipping
				return false
			end
		else
			-- No entries in the leaderboard, prevent equipping
			return false
		end
	else
		-- Failed to fetch leaderboard, prevent equipping
		warn("Failed to fetch leaderboard.")
		return false
	end
end

local function onCheckDataStoreRequest(player)
	local canEquip = checkDataStoreAndEquipPet(player)
	-- Fire RemoteEvent back to the client with the result
	PetCheckerEvent:FireClient(player, canEquip)
end

EquipPetEvent.OnServerEvent:Connect(function(player, petId)
	local donatorPet = game.ReplicatedStorage.DragonCompanion_4
	local playerCharacter = player.Character
	if playerCharacter and petId == "pet_Donator" then
		local canEquip = checkDataStoreAndEquipPet(player)
		if canEquip then
			-- Player can equip, proceed with equipping the pet
			local donatorPetClone = donatorPet:Clone()
			donatorPetClone.Parent = playerCharacter

			-- Move pet's position on the server
			coroutine.wrap(function()
				MovePet(player, donatorPetClone)
			end)()
		else
			-- Player cannot equip, prevent equipping
			print("Player is not the first on the leaderboard, prevent equipping of the pet.")
		end
	end
end)

RemovePetEvent.OnServerEvent:Connect(function(player, petId)
	local playerCharacter = player.Character
	if playerCharacter and petId == "pet_Donator" then
		RemovePlayerPets(player)
	end
end)

game.Players.PlayerAdded:Connect(function(player)
	-- Listen for requests to check DataStore and equip pet
	PetCheckerEvent.OnServerEvent:Connect(function()
		onCheckDataStoreRequest(player)
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	RemovePlayerPets(player)
end)

Client Side

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local EquipPetEvent = ReplicatedStorage:WaitForChild("EquipPetEvent")
local RemovePetEvent = ReplicatedStorage:WaitForChild("RemovePetEvent")
local PetCheckerEvent = ReplicatedStorage:WaitForChild("DonatorPetChecker")
local player = game.Players.LocalPlayer
local button = script.Parent
local petId = "pet_Donator"
local wasPetEquippedBeforeDeath = false

-- Function to update button text based on gamepass ownership
local function UpdateButtonText()
	button.Text = wasPetEquippedBeforeDeath and "Unequip" or "Equip"
end

-- Function to handle cloning or removing the pet
local function TogglePet()
	if button.Text == "Equip" then
		-- If pet is not equipped, equip it
		EquipPetEvent:FireServer(petId)
		wasPetEquippedBeforeDeath = true -- Update the variable since the pet is now equipped
		button.Text = "Unequip" -- Change button text to "Unequip"
	else
		-- If pet is equipped, remove it
		RemovePetEvent:FireServer(petId)
		wasPetEquippedBeforeDeath = false -- Update the variable since the pet is now removed
		button.Text = "Equip" -- Change button text to "Equip"
	end
end

-- Listen for player character removal (death)
player.CharacterRemoving:Connect(function(character)
	if wasPetEquippedBeforeDeath then
		-- If pet was equipped before death, re-equip it upon respawn
		EquipPetEvent:FireServer(petId)
	end
end)

-- Function to handle firing RemoteEvent to check DataStore
local function checkDataStoreAndEquipPet()
	PetCheckerEvent:FireServer()
end

-- Function to handle the result of the DataStore check
local function onCheckDataStoreResult(canEquip)
	if canEquip then
		TogglePet()
	else
		button.Text = "Locked"
		print("You do not have the highest value in the DataStore.")
	end
end

button.MouseButton1Click:Connect(checkDataStoreAndEquipPet)

PetCheckerEvent.OnClientEvent:Connect(onCheckDataStoreResult)

player.CharacterAdded:Connect(function(character)
	UpdateButtonText()
	checkDataStoreAndEquipPet()
end)

-- Immediately update button text when the script runs
UpdateButtonText()
checkDataStoreAndEquipPet()

I’m not sure how to fix this, it keeps saying I’m not the first person on the leaderboard and it won’t let me equip it.

1 Like

I need a real solution, not a ChatGPT reply.

ahah it’s not chatgpt but I can understand that it didn’t necessarily help, hoping that someone can help you