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

Help with hit remove?

Asked by
KordGamer 155
9 years ago

I was writing a script that removes a part named "Gold" or "Xp" when it touches it. This is the code :

script.Parent.Touched:connect(function(hit)
    print(hit)
    if hit.Name == "XP" or "Gold" then
        print("ye")
                hit:remove()
    else
        print("nope")
    end
end)

It doesn't work, and it removes the player instead. Can you help me with this?

Any help is appreciated. Thanks!

2 answers

Log in to vote
1
Answered by
woodengop 1134 Moderation Voter
9 years ago

You made a small Mistake on line 03, Let me show you:

script.Parent.Touched:connect(function(hit)
    if hit.Name=="XP" or hit.Name=="Gold" then-- on the gold part.
        hit:remove()
    end
end)
0
This is my 100 Answer. woodengop 1134 — 9y
Ad
Log in to vote
1
Answered by
ImageLabel 1541 Moderation Voter
9 years ago

The only problem I noticed at first glance was the checking of the Name property's value. Also, since you want the hit to be from a part, i added a check for hit's ClassName using the IsA method.


If the first argument is false or nil (the name isn't 'XP' in this context), the or operator returns the second argument, which is a string (true, because it isn't nil or false).

if (false or true) then
    --will run because true

if (nil or true) then
    --will run because true

If the first argument is true, it is returned and the second argument is ignored.

if (true or true) then
    --will also run because true

The statement then only checks for whether or not the Name is XP. Here's are examples on how to work around this

  1. Check by typing out the property you are assessing after the or
    script.Parent.Touched:connect(function (hit)
        if hit:IsA('BasePart') then
            if hit.Name == 'XP' or hit.Name == 'Gold' then
                warn('Destroy')
            else
                -- not a match
            end
        end
    end)
  1. Tables
    Names = {'XP', 'Gold'} 
    script.Parent.Touched:connect(function (hit)
        if hit:IsA('BasePart') then
            if Names[hit.Name] then
                warn('Destroy')
            else
                -- not a match
            end
        end
    end)

Answer this question