Trash spawns but doesnt have script in it

I set up a system where when a player touches Trash1, it disappears, and a new one spawns. However, the newly spawned Trash1 doesn’t disappear when touched because it doesn’t have the script inside it. Also, the new Trash1 doesn’t keep the texture/image I originally applied.
Additionally, Trash1 is a mesh part that I obtained from the internet. I tried using the built in AI but I think it made it worse.

This script is in trash1 so it affect stinkpoints(a currency shown in leaderboard:

local object = script.Parent

object.Touched:Connect(function(hit)
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player then
		
		local leaderstats = player:FindFirstChild("leaderstats")
		if not leaderstats then
			leaderstats = Instance.new("Folder")
			leaderstats.Name = "leaderstats"
			leaderstats.Parent = player
		end

		
		local stinkPoints = leaderstats:FindFirstChild("StinkPoints")
		if not stinkPoints then
			stinkPoints = Instance.new("IntValue")
			stinkPoints.Name = "StinkPoints"
			stinkPoints.Value = 0
			stinkPoints.Parent = leaderstats
		end

		
		stinkPoints.Value = stinkPoints.Value + 5

		
		object:Destroy()
	end
end)


This is in serverscriptservice and it tells where to spawn:

local object = game.Workspace.Trash1

function getRandomPosition()
	local minX, maxX = -1248, -1244 
	local minZ, maxZ = -50, -46     
	local yHeight = -101.361        

	return Vector3.new(math.random(minX, maxX), yHeight, math.random(minZ, maxZ))
end

function spawnObject()
	local newObject = object:Clone()
	newObject.Parent = workspace

	-- Position the object within the defined range
	newObject.Position = getRandomPosition()

	-- Despawn after 15 seconds
	task.delay(15, function()
		if newObject then
			newObject:Destroy()
		end
	end)
end

while true do
	task.wait(5) -- Adjust spawn frequency
	spawnObject()
end

Sorry if its hard to understand!

Is the script parented under Trash1?

1 Like

its better to put the code inside the function inside .Touched into a function in the same script as the spawner, and then call this function for each object that is spawned

you can pass the newly spawned object as a parameter to the function

--example pseudocode
local function handleTouching(object) -- this would be the part inside .Touched
end

local newObject = spawnObject() -- return the new object in your spawn object function
handleTouching(object) -- pass the object

yes, the script is parented under trash1

Move Trash1 to ReplicatedStorage, script and all.

--local object = game.Workspace.Trash1
local object = game:GetService("ReplicatedStorage").Trash1

Tested and working.

You’re defining trash1 on the workspace. If the player happens to touch that one It starts to error.
So just make it so the player can’t touch that one. ReplicatedStorage is the norm for Cloning.

1 Like

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