LocalScript (客戶端腳本)
Empty
Empty
Empty
LocalScript 是一段僅在玩家的計算機(客戶端)上運行的程式碼。
Empty
Empty
Empty
它處理與本地玩家相關的事情,比如用戶介面互動、攝影機控制和不需要所有人看到的效果。
Empty
Empty
Empty
用戶介面 (UI) 互動 | 更新或與 GUI 元件互動 |
玩家輸入 | 玩家輸入,例如鍵盤、滑鼠或遊戲手柄事件。 |
本地效果 | 特定於本地玩家的視覺或音訊效果 |
本地資料處理 | 本地設置或偏好,庫存管理 |
Empty
Empty
Empty
回應速度 | 在客戶端上運行,使其對玩家的操作回應更加靈敏。延遲最小,因為它不需要與伺服器通信以檢測輸入。 |
效率 | 在本地處理事件,減輕伺服器負擔,這在有許多玩家的遊戲中特別重要。 |
Empty
Empty
Empty
-- LocalScript in StarterPlayerScripts
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local player = Players.LocalPlayer
local givePointsEvent = ReplicatedStorage:WaitForChild("GivePointsEvent")
local function triggerGivePoints(points)
givePointsEvent:FireServer(points)
end
-- Example usage: Trigger the event when the player clicks a GUI button
local screenGui = Instance.new("ScreenGui", player:WaitForChild("PlayerGui"))
local button = Instance.new("TextButton", screenGui)
button.Size = UDim2.new(0, 200, 0, 50)
button.Position = UDim2.new(0.5, -100, 0.5, -25)
button.Text = "Get Points"
button.MouseButton1Click:Connect(function()
triggerGivePoints(10)
end)
Empty
Empty
Empty
-- Script in ServerScriptService
-- Get the RemoteEvent
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local givePointsEvent = ReplicatedStorage:WaitForChild("GivePointsEvent")
-- Function to handle the remote event
local function onGivePoints(player, points)
-- Add points to the player's leaderstats
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
local score = leaderstats:FindFirstChild("Points")
if score then
score.Value = score.Value + points
print(player.Name .. " received " .. points .. " points!")
end
end
end
-- Connect the function to the OnServerEvent of the remote event
givePointsEvent.OnServerEvent:Connect(onGivePoints)