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

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

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

✓ Accepted answer

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

###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.

1 comment

0

So the event was only connected to the first explosion and none else?

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