Is there a better way to do this?

hey! ive been trying to get this silly little thing to work, and its probably so easy but i am simply not smart.

-- in localscript
local plat = game.ReplicatedStorage.platform
local uip = game:GetService("UserInputService")
local Players = game:GetService("Players")
local canspawn = true
local waiting = 0




uip.InputBegan:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Q and canspawn == true then
		local plr = Players.LocalPlayer
		local hrp = plr.Character:WaitForChild("HumanoidRootPart")
		local ncf = CFrame.new(hrp.Position) + Vector3.new(0, -2, 0)
		print("ncf")
		canspawn = false
		local clone = plat:Clone()
		clone.Parent = workspace
		clone.CFrame = ncf
		while true do
			waiting = waiting +1
			clone.CFrame = clone.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.5, 0)
			print("aaaaffefe")
			wait()
			if waiting == 147 then
				waiting = 0
				break
			end
		end
		canspawn = true
		wait(0.05)
		clone:Destroy()
	end
	
end)

ignoring the lack of coding skills, the main issue here it the while true loop, simply trying to make the part spin when its spawned. ive attempted to have the loop in a different script but theres the whole ordeal with cloning scripts from a localscript. ive also tried coroutines but i couldnt figure it out. It technically works but its very flimsy and i know there are ways several times better. ty!

1 Like

Can you maybe give a little more context of what you are trying to achieve? Maybe I can help better that way.
The 147 for example seems to be very specific.

If you want to make the code more clean you can replace the while true loop with a for loop.

1 Like

Just as @SirteXx said, you could use a for loop
I’ve edited your script a little

Edited Code
local plat =  game:GetService("ReplicatedStorage").platform
local uip = game:GetService("UserInputService")
local player = game:GetService("Players").LocalPlayer

local canSpawn = true
uip.InputBegan:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Q and canSpawn == true then
		canSpawn = false
		
		local hrp = player.Character:WaitForChild("HumanoidRootPart")
		local clone = plat:Clone()
		clone.Parent = workspace
		clone.CFrame = CFrame.new(hrp.Position) + Vector3.new(0, -2, 0)
		
		for i = 1, 147 do
			clone.CFrame = clone.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.5, 0)
			task.wait()
		end
		
		canSpawn = true
		task.wait(0.05)
		clone:Destroy()
	end
end)

You can use task.spawn, its easier to work with

Example with task.spawn
In this case 2 would show first

task.spawn(function()
	task.wait(1)
	print(1)
end)

print(2)
2 Likes

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