客戶端腳本

LocalScript (客戶端腳本)

LocalScript 是一段僅在玩家的計算機(客戶端)上運行的程式碼。

它處理與本地玩家相關的事情,比如用戶介面互動、攝影機控制和不需要所有人看到的效果。

用戶介面 (UI) 互動更新或與 GUI 元件互動
玩家輸入玩家輸入,例如鍵盤、滑鼠或遊戲手柄事件。
本地效果特定於本地玩家的視覺或音訊效果
本地資料處理本地設置或偏好,庫存管理
回應速度在客戶端上運行,使其對玩家的操作回應更加靈敏。延遲最小,因為它不需要與伺服器通信以檢測輸入。
效率在本地處理事件,減輕伺服器負擔,這在有許多玩家的遊戲中特別重要。
-- 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)
-- 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)

如果您覺得本教程對您有幫助,並且願意支持我的工作,請考慮請我喝杯咖啡。

非常感謝您的支持!

請我喝杯咖啡