Handling Event on Client for part that's created on Server

I have this situation where I have a part that is being created on the server-side when any player press Shift. And I am handling the effects on the Client-side. The effects on the Client-side will be triggered when the player or something touches the part. Then after 10seconds, the parts get destroyed.

The problem is the part is inserted but on the Client-side the touch event is not registering because the part is only there temporally so the event can’t just be fixed.

How can I go about making this work and having the part being created on the server while I handle the effects on the Client?

Code:

--Local script
local RS = game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
local test = RS:WaitForChild("RE_Test")

UIS.InputBegan:connect(function(inst)
	if inst.KeyCode == Enum.KeyCode.LeftShift then
		test:FireServer()
		
		--Handling effects on client
		local partToDetect = game.Workspace:FindFirstChild("Part")
		if  partToDetect ~= nil then
			print("Detecting")
			partToDetect.Touched:Connect(function(touched)
				partToDetect.BrickColor.random()
			end)
		end

	end
end)

--Server Script
local RS = game:GetService("ReplicatedStorage")
local createPartEvent = RS:WaitForChild("RE_Test")

local function onCreatePartFired(player)
	print("Fierd Server")
	
	--Creating Part Securly On server
	local part = Instance.new("Part")
	part.Parent = game.Workspace
	
	wait(10)
	
	part:Destroy()
end

createPartEvent.OnServerEvent:Connect(onCreatePartFired)

LocalEffect.rbxl (22.0 KB)

Replace FindFirstChild with WaitForChild. I’d also recommend giving the part a different name to make sure that the correct part is found on the client. For example, the player’s userid could be the name of the part.

I can’t go about doing so because with :WaitForChild() it will put an infinite yield if the player do not press shift. Thanks for the advice to not leave it as “Part” I put together a quick scenario just to make things simple that’s why I left it named as part

Well it seems like you only define part when the player has pressed shift, so I don’t understand what you mean. Anyways, you can give WaitForChild a timeout. You could also use a remote function or a two way remote event to send the created part to the client.

In order to reduce the potential lag, I am trying to do it stand alone on the Client-side, and returning a remote function would be defeating the whole point

Well can’t you still use WaitForChild with timeout?

If you want the part to be specific to the player and only do the effect for the caller player, you’d just have the remote return the part to the client.

Otherwise, you could try using CollectionService.
On the Server side, create the Part, put it under workspace, then tag the part with a specific ID.
On the Client side, you can use CollectionService’s GetInstanceAddedSignal to detect the object as special when it is created.

1 Like