RemoteEvents let players send messages to the server. We need one for voting!
Add this Script to ServerScriptService:
-- Voting System (Server Script)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local VoteEvent = ReplicatedStorage:WaitForChild("VoteEvent")
-- Store votes: {playerName = voteCount}
local votes = {}
local hasVoted = {}
VoteEvent.OnServerEvent:Connect(function(player, votedForName)
-- Each player can only vote once
if hasVoted[player.Name] then
return
end
hasVoted[player.Name] = true
-- Count the vote
if not votes[votedForName] then
votes[votedForName] = 0
end
votes[votedForName] = votes[votedForName] + 1
print(player.Name .. " voted for " .. votedForName)
end)
-- Function to find who won the vote
local function getVoteWinner()
local winner = nil
local highestVotes = 0
for playerName, voteCount in pairs(votes) do
if voteCount > highestVotes then
highestVotes = voteCount
winner = playerName
end
end
return winner
end This creates voting buttons for each player. Add a LocalScript to StarterGui:
-- Voting UI (LocalScript in StarterGui)
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local player = Players.LocalPlayer
local VoteEvent = ReplicatedStorage:WaitForChild("VoteEvent")
local function showVotingUI()
local gui = Instance.new("ScreenGui")
gui.Name = "VotingUI"
local title = Instance.new("TextLabel")
title.Size = UDim2.new(0.4, 0, 0.1, 0)
title.Position = UDim2.new(0.3, 0, 0.1, 0)
title.Text = "Who is the Parseltongue speaker?"
title.TextScaled = true
title.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
title.TextColor3 = Color3.fromRGB(255, 255, 255)
title.Parent = gui
-- Create a button for each player
local yPosition = 0.25
for _, otherPlayer in pairs(Players:GetPlayers()) do
if otherPlayer ~= player then
local button = Instance.new("TextButton")
button.Size = UDim2.new(0.3, 0, 0.08, 0)
button.Position = UDim2.new(0.35, 0, yPosition, 0)
button.Text = otherPlayer.Name
button.TextScaled = true
button.BackgroundColor3 = Color3.fromRGB(50, 100, 50)
button.TextColor3 = Color3.fromRGB(255, 255, 255)
button.Parent = gui
button.MouseButton1Click:Connect(function()
VoteEvent:FireServer(otherPlayer.Name)
gui:Destroy()
end)
yPosition = yPosition + 0.1
end
end
gui.Parent = player.PlayerGui
end
-- You'll call showVotingUI() when it's voting time!