I have a sword that does damage. The damage the sword deals is subtracted by the player hit defense. The value for the player's defense is stored in another value called "Data" inside the player. Only it keeps saying data is nil so I'm not sure what to do.
player = game.Players.LocalPlayer Tool = script.Parent Tool.Handle.Touched:connect(function(hit) ehum = hit.Parent:FindFirstChild("Humanoid") local damage = 5 local hitPlayer = game.Players:getPlayerFromCharacter(hit.Parent) if hitPlayer ~= nil then damage = damage - hitPlayer.Data.DefVal.Value end ehum:TakeDamage(damage) end)
You will want to create a check to make sure that hit
is actually part of a Character
before you assume hit.Parent
is the Character
. This can be accomplished using an If statement
.
if hit.Parent:FindFirstChild("Humanoid") then -- rest of my code here end
Your first variable ehum
, tries to find a Humanoid
within its parent. Though if Tool.Handle
touches anything that doesn't have a Humanoid
in its parent, the script will error. This goes for the rest of the variables as well. This can be solved with the code above.
Also, there could be a chance that the Client is trying to directly change values within another Client, which would especially not work with FilteringEnabled
turned on.
Here's a link to a Wiki Page about RemoteEvents
, in case this is also an issue:
Hope this helps!
If this answer helped or solved your issue, don't forget to upvote and confirm
EDIT: In response to your comments, I have no issue getting the Character
who was hit by Tool.Handle
using the following code:
player = game.Players.LocalPlayer Tool = script.Parent Tool.Handle.Touched:connect(function(hit) if hit.Parent:FindFirstChild("Humanoid") then local ehum = hit.Parent:FindFirstChild("Humanoid") local damage = 5 local hitPlayer = game.Players:GetPlayerFromCharacter(hit.Parent) print(hitPlayer) if hitPlayer ~= nil then damage = damage - hitPlayer.Data.DefVal.Value end ehum:TakeDamage(damage) end end)