Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to count the number of times an object been hit?

Asked by 7 years ago

Making a script that when someone hits an object a certain amount of times (5 right now) the object's CanCollide will turn false.

numOfHits = 0

function onTouched(hit)
    script.Parent.BrickColor = BrickColor.new("Really red")
    script.Parent.Deflect:Play()
    numOfHits = 1+
    if numOfHits == 5 then
        script.Parent.CanCollide = false
    else
        wait(0.05)
        script.Parent.BrickColor = BrickColor.new("Lime Green")
    end
end

script.Parent.Touched:connect(onTouched)

The script doesn't work but if I get rid of line 6 it works but doesn't count the number of times it's been hit therefore doesn't turn it's NoCollide to false.

2 answers

Log in to vote
1
Answered by 7 years ago

Ok, so let's say I had a number and I wanted to increase it. This is what I would do:

local num = 0

num = num + 1 -- Basically, this takes 'num' and makes it equal to itself although it adds one to it's previous state. So if it's previous state is 0, it would add 1 and it would become 1. If it's previous state is 104, it would add 1 and it would become 105.

Here's your script fixed:

numOfHits = 0

function onTouched(hit)
    script.Parent.BrickColor = BrickColor.new("Really red")
    script.Parent.Deflect:Play()
    numOfHits = numOfHits + 1 -- That's all you had to do to fix it.
    if numOfHits == 5 then
        script.Parent.CanCollide = false
    else
        wait(0.05)
        script.Parent.BrickColor = BrickColor.new("Lime Green")
    end
end

script.Parent.Touched:connect(onTouched)

Hope I helped, if I did be sure to accept my answer :)

0
It works now, thanks! :) MasterKnight555 35 — 7y
Ad
Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

"1+" is not a valid way to add one. To fix your issue, use this method:

variable = 1
variable = variable + 1

This sets the already existing variable to itself plus one. It may seem confusing at first but here is another way to look at it:

variable = 1
num = variable + 1

variable = num

I hope this helps.

Answer this question