Roblox开发中NPC Humanoid.health始终显示100与实际值不符问题求助
问题原因
- 当前代码仅判断了自身角色的生命值
me.Health,没有对命中的NPC的Humanoid生命值做校验,只要自身生命值大于0就会触发射击逻辑,和需求不符。 - Roblox官方Humanoid的生命值属性为大写开头的
Health,如果其他逻辑中使用小写health读取,会读取到自定义属性而非官方生命值,默认值固定为100。 - 生命值修改端不匹配:如果在客户端LocalScript中修改NPC生命值,服务器端Script无法读取该修改,只会返回服务器存储的初始生命值100,Roblox仅同步服务器侧修改的属性到全端。
- 路径获取错误:如果
me的层级路径写错,可能会误取到其他单位的Humanoid,导致生命值始终为100。
修复代码
-- 请确保该脚本为服务器Script,不要放置在客户端运行 me = script.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid") function touched(hit) -- 自身不存在或已死亡直接退出 if not me or me.Health <= 0 then return end -- 获取命中目标的Humanoid local targetHumanoid = hit.Parent:FindFirstChild("Humanoid") if targetHumanoid then -- 目标已死亡直接退出,不触发射击 if targetHumanoid.Health <= 0 then return end script.Parent.Parent.shoot.Shotgun:Play() script.Parent.Parent.shoot.Transparency = 0 script.Parent.Parent.shoot.CanTouch = true task.wait(0.2) script.Parent.Parent.shoot.Transparency = 1 script.Parent.Parent.shoot.CanTouch = false task.wait(0.05) script.Parent.Position += Vector3.new(0,200,0) task.wait() script.Parent.Position -= Vector3.new(0,200,0) end end script.Parent.Touched:Connect(touched)
关键修改说明
- 新增目标NPC生命值判断逻辑,目标死亡时直接终止函数不执行射击流程
- 替换过时的
wait()为官方更推荐的task.wait(),避免计时误差 - 新增
me存在性校验,避免对象销毁后报错 - 所有对NPC生命值的修改必须放在服务器Script中执行,禁止在LocalScript中修改NPC属性
- 不要创建和官方属性同名的小写
health自定义属性,避免读取冲突
内容的提问来源于stack exchange,提问作者galli
相关产品推荐
相关产品推荐

