You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox战斗系统报错:attempt to index nil with 'TakeDamage'求助

Roblox战斗系统报错修复:attempt to index nil with 'TakeDamage'

错误原因分析

  • 获取敌人Humanoid的逻辑完全错误:你当前代码里Hitbox.Parent是玩家角色下的[玩家名]Melee文件夹,从这里找Humanoid必然返回nil,根本不是敌人的Humanoid。
  • 判断条件写错:你用if Humanoid then做判断,这里的Humanoid是玩家自己的角色人形对象,永远不为空,导致不管有没有找到敌人Humanoid,都会执行enemyHumanoid:TakeDamage(Damage),最终触发nil调用方法的错误。

修复方案

  1. 修正敌人Humanoid的获取路径:从碰撞到的部件Hit向上查找,找到它所属的角色模型,再从模型里获取Humanoid。
  2. 修正判断条件:判断是否成功获取到敌人的Humanoid,只有存在时才执行伤害逻辑。
  3. 可选优化:增加对敌人Humanoid存活状态的判断,避免对已死亡角色重复处理。

修正后的完整代码

local rp = game:GetService("ReplicatedStorage")
local Combat = rp:WaitForChild("Combat")

local Debris = game:GetService("Debris")

local Animations = script:WaitForChild("Animations")
local Meshes = script:WaitForChild("Meshes")

local anims = 
    {
        Animations:WaitForChild("Right"),
        Animations:WaitForChild("Left"),
        Animations:WaitForChild("Gut"),
        Animations:WaitForChild("Kick"),
    }

local limbs = 
    {
        "RightHand",
        "LeftHand",
        "RightHand",
        "RightFoot"
    }

local Damage = 10
Combat.OnServerEvent:Connect(function(player,count)
    local Character = player.Character
    local Humanoid = Character:WaitForChild("Humanoid")
    
    local attack = Humanoid:LoadAnimation(anims[count])
    attack:Play()
    
    local Limb = Character:WaitForChild(limbs[count])
    
    local folder = Instance.new("Folder",Character)
    folder.Name = player.Name.."Melee"
    
    local Hitbox = Meshes:WaitForChild("Hitbox"):Clone()
    Hitbox.CFrame = Limb.CFrame
    Hitbox.Parent = folder
    Debris:AddItem(Hitbox,.5)
    
    local weld = Instance.new("ManualWeld")
    weld.Part0 = Hitbox
    weld.Part1 = Limb
    weld.C0 = weld.Part0.CFrame:ToObjectSpace(weld.Part1.CFrame)
    weld.Parent = weld.Part0
    
    Hitbox.Touched:Connect(function(Hit)
        if Hit:IsA("BasePart") then
            if not Hit:IsDescendantOf(Character) then
                -- 从碰撞部件向上查找角色模型,再获取Humanoid
                local enemyCharacter = Hit:FindFirstAncestorOfClass("Model")
                local enemyHumanoid = enemyCharacter and enemyCharacter:FindFirstChildOfClass("Humanoid")
                -- 判断是否获取到有效的敌人Humanoid,且处于存活状态
                if enemyHumanoid and enemyHumanoid.Health > 0 then
                    Hitbox:Destroy()
                    enemyHumanoid:TakeDamage(Damage)
                end
            end
        end
    end)
        
    Combat:FireClient(player)
end)

内容的提问来源于stack exchange,提问作者Bizarre_boyMan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:45:34