You need to enable JavaScript to run this app. Roblox开发中NPC Humanoid.health始终显示100与实际值不符问题求助
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 05:45:05