Changing target of Touched function?

Hiya DevForum! Amateur programmer here, and I was wondering if I could change the target of a Touched function (aka change the part that activates it) inside a single script for a seamless generation-type thing, but I’m open to using things like RemoteEvents or RemoteFunctions if that will make it any easier. I’ve looked all over the DevForum for this type of question, but I can’t seem to find anything, so that’s why I’m making this post.

Here’s my code:

local rooms = game:GetService("ReplicatedStorage"):WaitForChild("rooms"):GetChildren()
local debounce = false

local currentRoomSelection = rooms[math.random(1,#rooms)]
local currentRoom = currentRoomSelection:Clone()
currentRoom.Parent = game.Workspace
currentRoom:PivotTo(game.Workspace.startExit.CFrame)
local oldRoom = currentRoom
currentRoomSelection = rooms[math.random(1,#rooms)]
currentRoom = currentRoomSelection:Clone()
currentRoom.Parent = game.Workspace
currentRoom:PivotTo(oldRoom.Exit.CFrame)
oldRoom = currentRoom
local roomsGenerated = 2
local generatorPart = currentRoom.Entrance

currentRoom.Entrance.Touched:Connect(function()
	if debounce == false then
		debounce = true
		oldRoom = currentRoom
		currentRoom.Entrance:Destroy()
		currentRoomSelection = rooms[math.random(1,#rooms)]
		currentRoom = currentRoomSelection:Clone()
		currentRoom.Parent = game.Workspace
		currentRoom:PivotTo(oldRoom.Exit.CFrame)
		roomsGenerated += 1
		print("Rooms generated: "..roomsGenerated)
		debounce = false
	end
end)

Thanks for the help!

I’m not exactly sure what you want to do. You can used a .Touched event on any part

The Touched event provides the actual part that hit the part you’re detecting touches with.

You just need to change this line right here:

currentRoom.Entrance.Touched:Connect(function()

To this:

currentRoom.Entrance.Touched:Connect(function(hitPart)

“hitPart” is a variable that represents the part that hit the Entrance part.

You can check for the part’s name for example if you’d like. Let’s say we only want the function to run if the part’s name is Activator. You’d just do this:

currentRoom.Entrance.Touched:Connect(function(hitPart)
	if debounce == false and hitPart.Name == "Activator" then

All you have to do is just change the conditional statement that checks whether or not debounce is false.

Oh, I don’t even know why I didn’t think of this. Thanks!

1 Like