我编写了一些代码,允许玩家喝一口 StarterPack 中的“OrangeJuiceTool”项目,每当喝一口时,脚本中的 Sips 值都会更新并添加一个,但是每当喝一口时,不添加任何值。这是我的代码:
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("TimeStats")
game.Players.PlayerAdded:Connect(function(Player)
local Leaderstats = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
Leaderstats.Parent = Player
local Sips = Instance.new("IntValue")
Sips.Name = "Sips"
Sips.Value = 0
Sips.Parent = Leaderstats
local tool = game.StarterPack:WaitForChild("OrangeJuiceTool")
local Data = DataStore:GetAsync(Player.UserId)
if Data then
Sips.Value = Data
end
local function IncrementSips()
Sips.Value = Sips.Value + 1
end
tool.Equipped:Connect(IncrementSips)
Player.CharacterAdded:Connect(function(Character)
local Tool = Character:FindFirstChildOfClass("Tool")
if Tool and Tool.Name == "OrangeJuiceTool" then
Tool.Activated:Connect(IncrementSips)
end
end)
end)
game.Players.PlayerRemoving:Connect(function(Player)
DataStore:SetAsync(Player.UserId, Player.leaderstats.Sips.Value)
end)
我尝试用不同的功能更新代码,但没有成功:(
Player.CharacterAdded:Connect(function(Character)
local Tool = Character:FindFirstChildOfClass("Tool")
if Tool and Tool.Name == "OrangeJuiceTool" then
Tool.Activated:Connect(IncrementSips)
end
end)
应该是:
local Backpack = Player:FindFirstChildOfClass("Backpack")
Player.CharacterAdded:Connect(function(Character)
local Tool = Backpack:WaitForChild("OrangeJuiceTool")
Tool.Activated:Connect(IncrementSips)
end)
工具只有在玩家装备后才会添加到角色对象中。并且
CharacterAdded
仅在玩家第一次生成时运行。因此,即使玩家稍后装备了工具,该代码也已经在 Tool
为 nil
的位置运行。