Math.random remembers previous part

Hey guys.

While making a delivery type game, I ran into an issue. Using math.random to randomly select a delivery location, it remembers the previous part.

Lets say the red brick in the very left turned green. I step on it and it turns back to red.
I trigger the proximity prompt, giving me a random part to turn green.
Now the one in the very right turns green.
But, if I stepped on the one in the very left, it would turn the one to the very right red dispite it not being the one that turned green.

Heres the code:

local proximityprompt = script.Parent.ProximityPrompt

local foldercontainingdeliverypoints = game.Workspace.deli
local randomdelievery = foldercontainingdeliverypoints:GetChildren()



proximityprompt.Triggered:Connect(function(plr)
		
	local randomPart = randomdelievery[math.random(1, #randomdelievery)] -- select random part
	
	randomPart.BrickColor = BrickColor.new(0, 255, 0) -- turns random part to green
	
	randomPart.Touched:Connect(function() 
		randomPart.BrickColor = BrickColor.new(151, 0, 0) -- turns it back to red
		print("Yay! You turned it red.")
	end)
		
end)

Why is this happening?

When you trigger the proximityprompt you are connecting a touched event and not disconnecting it ever, which means every time you touch that part it will turn it red. You have to disconnect the function after you touch it. It would look something like this:

local proximityprompt = script.Parent.ProximityPrompt

local foldercontainingdeliverypoints = game.Workspace.deli
local randomdelievery = foldercontainingdeliverypoints:GetChildren()

local touchedevent

proximityprompt.Triggered:Connect(function(plr)
		
	local randomPart = randomdelievery[math.random(1, #randomdelievery)] -- select random part
	
	randomPart.BrickColor = BrickColor.new(0, 255, 0) -- turns random part to green
	
	touchedevent = randomPart.Touched:Connect(function() 
		randomPart.BrickColor = BrickColor.new(151, 0, 0) -- turns it back to red
		print("Yay! You turned it red.")
        touchedevent:Disconnect()
	end)
		
end)
1 Like