Need help making this more efficient

Heyo I’m trying to make a little run particle for running like in mario odyssey and I’d like some help making my code better.

This is what I currently have

--| Services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")
local RepStorage = game:GetService("ReplicatedStorage")

--| Variables
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local HRP = Character:WaitForChild("HumanoidRootPart")
local SmokeLeft = RepStorage:WaitForChild("FX")["Run Particles"].Left
local SmokeRight = RepStorage:WaitForChild("FX")["Run Particles"].Right

RunService.RenderStepped:Connect(function()
	if UIS:IsKeyDown(Enum.KeyCode.W) then
		if not HRP:FindFirstChild("Left") then
			Clone1 = SmokeLeft:Clone()		
			Clone1.Parent = HRP
		else
			HRP:FindFirstChild("Left").ParticleEmitter.Rate = 6
		end
		if not HRP:FindFirstChild("Right") then
			Clone2 = SmokeRight:Clone()		
			Clone2.Parent = HRP
		else
			HRP:FindFirstChild("Right").ParticleEmitter.Rate = 6
		end
	else
		if HRP:FindFirstChild("Left") then
			local Emitter = HRP:FindFirstChild("Left").ParticleEmitter 	
			spawn(function()
				for i = 6,0,-1 do
					Emitter.Rate = i
				end
				wait(1)
				if HRP:FindFirstChild("Left") and not UIS:IsKeyDown(Enum.KeyCode.W) then
					HRP:FindFirstChild("Left"):Destroy()					
				end				
			end)
		end
		if HRP:FindFirstChild("Right") then
			local Emitter = HRP:FindFirstChild("Right").ParticleEmitter 
			for i = 6,0,-1 do
				Emitter.Rate = i
			end
			wait(1)
			if HRP:FindFirstChild("Right") and not UIS:IsKeyDown(Enum.KeyCode.W) then
				HRP:FindFirstChild("Right"):Destroy()				
			end
		end
	end 
end)

This is the result

You can make your script more efficient by using Humanoid | Roblox Creator Documentation with GetPropertyChangedSignal() to detect if your character is walking/idle

2 Likes

If you are using the particle emitters throughout the entirety of your game, then you can create a script that gives the player the particle emitters with a rate of 0 any time their character spawns through the Player.CharacterAdded event. You can then simply change the rate as the character moves through the RenderStepped event instead of creating new particle emitters when the player starts to move and deleting them once their rate is at 0.

Instead of using RunService.RenderStepped, you could use the suggestion that @mymommakesbathbombs4 made, which will also make your code more efficient as it will only run when necessary instead of 60 times per second.

Didn’t even know this existed lol thanks