Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Variable won't update within damage script?

I have a simple damage script that deals damage to the player on touch, per usual. I have a variable for defense that is pulled from a NumberValue object that the player's character model gets when the player joins the server or respawns. However the defense variable within the script never updates. Any help?

function onTouched(hit)
	local human = hit.Parent:FindFirstChild("Humanoid")

	if (human ~= nil) then
		
		local Defense = hit.Parent.CharDefense
		
		local Damage = 1 - (Defense.Value / 100)
		print(Damage)
		human.Health = human.Health - Damage
		
	end
end

script.Parent.Touched:connect(onTouched)

2 comments

0

it works fine for me, check if you didnt misspell something or if you get any errors when you test it

0

I don't get any errors and the script does work. To be more specific, when the NumberValue for defense is updated in the player model, the value is not updated within the script. So every time damage is taken it is using the defense value the player had when the player joined the game, and never updating.

2 answers

✓ Accepted answer

How high is your Defence Value?

Try having the local value outside of the functions scope. That might be your problem.

6 comments

0

How would I go about doing this, since the parameter of the function is referenced when indexing the defense value? Thank you for your help!

0

HAve you tried what I said?

0

How would I go about doing what you are suggesting, is what I mean. I tried what I think you mean (moving the local Defense above the function) and it just breaks the script.

0

Ok, when you declare defence, put in the value instead of acessing it later. e.g.(Defence = CharDefence.Value)

0

Thank you for your help I figured it out

0

what did you do that worked?

try this, im not sure if it will work

script.Parent.Touched:Connect(function(hit)
    local human = hit.Parent:FindFirstChild("Humanoid")

    if (human ~= nil) then

        local Defense = hit.Parent.CharDefense

        local Damage = 1 - (Defense.Value / 100)
        print(Damage)
        human.Health = human.Health - Damage

    end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.