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

Script only works as soon as the game runs then never again?

Asked by 5 years ago

I want this script to work whenever it detects an explosion in the workspace. I have an explosion that goes off everytime I run my game to see the script work, but this is also the only time it will work. It will not run unless an explosion happens right when the game starts.

Thanks for the help.

local health = script.Parent.Parent.Parent.Health
local explosion = workspace:WaitForChild("Explosion")

local function onHit(part,distance)
        if part == script.Parent then
    health.Value = health.Value - 10
    print(health.Value)
    wait(3)
    script.Parent:Destroy()
    else
    end
end

explosion.Hit:connect(onHit)

2 answers

Log in to vote
2
Answered by
luachef 61
5 years ago
Edited 5 years ago

If you want to detect an explosion being added to workspace, you should simply use the event "ChildAdded". Here's what your script should look like:

local health = script.Parent.Parent.Parent.Health

local function onHit(part,distance)
    if part == script.Parent then
        health.Value = health.Value - 10
        print(health.Value)
        wait(3)
        script.Parent:Destroy()
    end
end

workspace.ChildAdded:Connect(function(child)--whenever something is created in workspace this event fires
    if child:IsA("Explosion") then-- we check if the child is an explosion
        child.Hit:Connect(onHit)--we connect the hit event to your function, so whenever something hits the explosion your function will run.
    end
end)

MORE INFO ON THE CHILDADDED EVENT: http://wiki.roblox.com/index.php?title=API:Class/Instance/ChildAdded

Ad
Log in to vote
1
Answered by 5 years ago

This is likely because line 2 is a reference to the first Explosion object in the game. So the Explosion.Hit event was connected to a function to the first explosion.

-- explosion creator inside your part
    local exp = Instance.new"Explosion"
    exp.Parent = game.Workspace
    exp.Position = script.Parent.Position 

    exp.Hit:Connect(function(hit, dist)
        if hit == script.Parent then
            -- code
            hit:Destroy()
        end
    end)

That was just an example of an explosion creator. When you Instance.new the explosion, connect the exp variable to the Hit event, so all new explosions fire the event.

0
So the event was only connected to the first explosion and none else? GlobeHousee 50 — 5y

Answer this question