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

How do i write an if statement with a _G?

I'm trying to write a script that when i get to a certain score, a wall will break. My score is stored as a _G and I'm using an if statement such as the one below to tell it when to break the wall but it's not working. I'm fairly new to scripting in Roblox so any help would be really appreciated.

local event = script.Parent
local pointlight = script.Parent.PointLight
_G.score = 0
local function onPartTouched(otherPart)
	partParent = otherPart.Parent
	local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")
	if humanoid then
		pointlight:Destroy()
		event:Destroy()
		 _G.score = _G.score + 1
		print(_G.score)
	end
end


event.Touched:Connect(onPartTouched)

This is what I have as the script storing the variable

local breakwall = game.Workspace.breakWall
local score = _G.score

if score == 1 then
	breakwall:Destroy()
end

To give any information that might help, the script that is breaking the wall is located in ServerScriptStorage

1 comment

0

Sorry if this might be confusing to read

1 answer

✓ Accepted answer

In the second script, what happens is that the script runs once, sees that _G.Score is 0 and then finishes. This is a very common mistake; you're assuming that the computer keeps checking when _G.Score changes, but it doesn't so you need to tell it to detect those changes.

Since you're using a variable instead of an IntValue you can't use the .Changed event that other objects have. You need to use a loop like so:

while wait(1) do
	if _G.Score >= 1 then
		breakwall:Destroy()
		break -- this stops the loop from running after the wall is broken, which frees up memory
	end
end

3 comments

0

Thank you, very thankful someone had the knowledge i was looking for. Now i can continue learning.

0

One more question, when i inserted the script, it didn't work still but i tinkered around a bit and the main thing that i could see was that the destroy part wasn't autofilling in so that might be a bi product of something else.

0

Have you defined breakwall? That might be the issue. Try putting print(This line is working!") between each line of code.

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