尝试将 nil 索引到“Takedamage”

问题描述 投票:0回答:1

问题是,我正在制作一个战斗系统,第 56 行的情况是:enemyHumanoid:TakeDamage(Damage),错误是:ServerScriptService.CombatSystem:56: attempts to index nil with 'TakeDamage' and我不知道该怎么办(这也是整个代码)

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
                local enemyHumanoid = Hitbox.Parent:FindFirstChild("Humanoid")
                if Humanoid then
                    Hitbox:Destroy()
                        
                    enemyHumanoid:TakeDamage(Damage)
                    
                end
            end
        end
    end)
        
    Combat:FireClient(player)
end)

我没有尝试很多,但总是出错。

roblox
1个回答
0
投票
如果 Humanoid 不存在,

:FindFirstChild("Humanoid")
返回 nil,这就是
enemyHumanoid:TakeDamage()
不起作用的原因。尝试使用此代码片段代替当前的 Hitbox.Touched 函数:

Hitbox.Touched:Connect(function(Hit)
    if Hit:IsA("BasePart") and not Hit:IsDescendantOf(Character) then
        local enemyHumanoid = Hitbox.Parent:FindFirstChild("Humanoid")
        if Humanoid then
            Hitbox:Destroy()

            if enemyHumanoid then -- Make sure enemyHumanoid exists and isn't nil
                enemyHumanoid:TakeDamage(Damage)
            end
        end
    end
end)
© www.soinside.com 2019 - 2024. All rights reserved.