How could I make the Touched Hit Run even without touching?

I Have a script with my code that detects if any player in the server touches a part. If the player touches the part. it Runs the code using hit.parent.humanoid Bla bla bla. But I have another script which I want to Also make the selected player run the script. but the script only takes ontouched input. not remotevent or fire? how could I run it both ways without breaking?

for _, Part in pairs(Scripted) do
	if Part:IsA("BasePart") then
		Part.Touched:Connect(
			function(hit)
			end
		)
	end
end

Thats Just the First Part of the script. the script is very big.

instead of having an anonymous function inside of the event, split it apart and define it. that way you can run it on touch plus being able to call said function whenever.

1 Like

What do you mean by that? Could you explain it more?

1 Like
for _, Part in pairs(Scripted) do
	if Part:IsA("BasePart") then
		Part.Touched:Connect(
			function(hit) -- instead of having this function declared inside of an event (anonymous) define it outside.
			end
		)
	end
end

-- MODIFIED --
function onHit(hit) --rename it. i named it onHit for this example.
    --do stuff in here
end

for _, Part in pairs(Scripted) do
	if Part:IsA("BasePart") then
		Part.Touched:Connect(onHit)
	end
end

-- Somewhere else.

onHit(randompart) --i call onhit and it does the same thing

Your gonna have to provide a parameter if you call it yourself. just know that.

1 Like

What does the randompart mean? Also how can I call the function in other scripts without having to touch the Selected Part?

1 Like

randompart is something you provide. since this originally ran off of a .Touched event which only returns a part, randompart is just a part that you defined somewhere else.

now, for functions being called in different scripts you can either use modules, or bindable functions.

https://developer.roblox.com/en-us/api-reference/class/ModuleScript
https://developer.roblox.com/en-us/api-reference/class/BindableFunction

too much for me to explain so your better off reading about it on your own.

2 Likes

Alrighty Thanks. I already have a module that handles it but I didnt notice I could just re use it. Thanks for sticking along and not one reply ghosting

2 Likes

welcome bro, since your using modules just know you cant bind a module function to an event. your gonna have to wrap it up inside of an anonymous function (i know :sad:).

heres an example

event:Connect(function(parameters)
    module.functionname(parameters)
end)
1 Like

You can connect ModuleScript functions to RBXScriptSignal objects via the instance method :Connect().

--SERVER

local module = require(script.ModuleScript)

local part = script.Parent

part.Touched:Connect(module.onTouched)
--MODULE

local module = {}

function module.onTouched(hit)
	print(hit.Name)
end

return module

file.rbxm (3.2 KB)

1 Like

woah i didnt know that. last time i tried it didn’t work for me :scream: cool!