求助:实现触碰部件每秒获1个leaderstat且离开停止的代码问题
解决Roblox触碰部件每秒获得1个Leaderstat的问题
你的代码存在两个核心问题:
- 全局变量
canGet会被所有玩家共享,且Touched事件会因玩家多个身体部位触碰部件而触发多次,导致同时运行多个while循环,每秒多次增加点数。 - 未监听
TouchEnded事件,玩家离开部件后无法停止点数增长。
以下是修正后的代码:
local part = script.Parent -- 用字典单独记录每个玩家的点数获取状态,避免多循环冲突 local playersInZone = {} local function onTouch(otherPart) local humanoid = otherPart.Parent:FindFirstChild("Humanoid") if not humanoid then return end local player = game.Players:GetPlayerFromCharacter(otherPart.Parent) -- 玩家不存在或已在获取点数时,直接返回 if not player or playersInZone[player] then return end playersInZone[player] = true -- 启动每秒加点数的循环 while playersInZone[player] do task.wait(1) -- 使用Roblox推荐的task.wait替代wait,性能更稳定 -- 增加存在性检查,避免玩家数据被销毁时报错 if player.leaderstats and player.leaderstats.Jump then player.leaderstats.Jump.Value += 1 end end end local function onTouchEnded(otherPart) local humanoid = otherPart.Parent:FindFirstChild("Humanoid") if not humanoid then return end local player = game.Players:GetPlayerFromCharacter(otherPart.Parent) if player then -- 移除玩家的状态标记,终止点数增长循环 playersInZone[player] = nil end end part.Touched:Connect(onTouch) part.TouchEnded:Connect(onTouchEnded)
关键改动说明:
- 用
playersInZone字典跟踪每个玩家的状态,确保单个玩家只会运行一个点数增长循环。 - 使用
GetPlayerFromCharacter替代名字查找玩家,是Roblox中获取角色对应玩家的标准方法,更可靠。 - 新增
TouchEnded事件监听,玩家离开部件时立即终止点数增长。 - 增加对
leaderstats和Jump值的存在性检查,避免玩家退出游戏后代码报错。
内容的提问来源于stack exchange,提问作者Jordy
相关产品推荐
相关产品推荐

