Script that fires when a part collides another part without inserting it into every model

is it possible to write a script that fires when an object collides another object without inserting it into each object

now i have something like this

local debounce = false
local module = require(game.ServerScriptService.SoundScript)
local model = script.Parent:GetChildren()

for i,v in pairs(model) do
	if v.ClassName  ~= "Script" then
		v.Touched:Connect(function(hit)
          if  debounce == false then
              debounce = true
              module.Sound(v)
              wait(.05)
              debounce = false
          end
      end)
	end
end

That’s what OOP is for, you have one main script that calls a constructor function in a module for each instance of that model, and that module assigns an “object” (just a table with functions and values) to that model. You can put the Touched event connection into that constructor function. For example:

-- MODULE SCRIPT
local soundModule = require(game:GetService("ServerScriptService").SoundScript)
local CollisionModule = {}
CollisionModule.__index = CollisionModule

-- Constructor function (creates the "object")
function CollisionModule.new(model : Model)
	-- Create a new "object" (basically just a table) and assign any variables/functions defined in CollisionModule to this table
	-- For example, you can use the function :IsBeingTouched() (defined below) on this table
	local self = setmetatable({}, CollisionModule)

	self.touchedDebounce = false -- Create a variable for this object to use for debouncing

	-- Listen for collisions
	for _,inst in model:GetChildren() do
		if not inst:IsA("BasePart") then continue end -- Only listen for collisions with Parts
		inst.Touched:Connect(function(hit)
			if self.touchedDebounce then continue end
			self.touchedDebounce = true
			soundModule.Sound(inst)
			task.wait(.05)
			self.touchedDebounce = false
		end)
	end
	return self
end

-- Just an extra function to demonstrate OOP, you don't need to use this. You can just directly use newObject.touchedDebounce
-- In the below server script this is written as newObject:IsBeingTouched()
function CollisionModule:IsBeingTouched()
	return self.touchedDebounce
end


return CollisionModule





-- SERVER SCRIPT
local collisionModule = require(--[[PATH HERE]])
local modelFolder = --[[PATH HERE]]

for _,model in modelFolder:GetChildren() do
	if not model:IsA("Model") then continue end -- Make sure you're using a model
	local newObject = collisionModule.new(model)
end

Any questions, let me know. I’ll be happy to help.

1 Like

It’s a little difficult for me to understand, but it works, thanks

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.