Hi, I am having a problem with a weapon sway script I made. There is a problem though, because the script does not work on your first life, but when you reset or die and spawn again, it starts working. Here is the script:
Maybe checking if the game loaded game.Loaded:Wait() or checking if the player character spawned game.Players.PlayerAdded.CharacterAdded:Wait() could work, not sure tho
try doing a for loop through each player instead of a event? the character is perhaps being loaded before the event can be recognized
somethin like this
for index, player in pairs(game.Players:GetPlayers()) do
if not player.Character then return end
game:GetService("RunService").RenderStepped:Connect(function()
local deltaX = game:GetService("UserInputService"):GetMouseDelta().X
deltaX = math.clamp(deltaX, -5, 5)
local deltaY = game:GetService("UserInputService"):GetMouseDelta().Y
deltaY = math.clamp(deltaY, -5, 5)
local targetFrame = CFrame.Angles(math.rad(deltaY), math.rad(deltaX), math.rad(deltaX))
game:GetService("TweenService"):Create(script.Parent.SwayCFrame, TweenInfo.new(0.125), {Value = targetFrame}):Play()
script.Parent.Handle.CFrame *= script.Parent.SwayCFrame.Value
end
I recommend you become familiar with RunService as it is quite useful. Just a quick fact as to why your code won’t work in this situation, you can tell OP’s script is a LocalScript because it uses the RenderStepped event which is client only. You should also know that the RenderStepped event has been replaced by the newly added PreRender event.
I think this is entirely due to replication, the character and animation are out-of-sync. RenderStepped will begin very quickly, PlayerAdded may be behind this instantiation so the connected function will bomb on first run. You need to make a manual connection to RenderStepped:Connect() upon load, or some self-imposed constraint (i.e. when you are sure all is good) and disconnect as and when you need. Connect PlayerAdded to a function call which begins render stepped with a return that you can disconnect at the appropriate time (i.e. PlayerRemoving() or whatever).
local connection = nil;
game:GetService("Players").PlayerAdded.CharacterAdded:Connect(function()
-- check the connection and deal with danglers before we fail on anything else.
if connection ~= nil then
connection:Disconnect();
connection = nil;
end
-- wait for replication
local timeout = 5;
local waittime = 0;
local interval = 0.1;
local value = script.Parent.SwayCFrame.Value;
while not value do
wait(interval);
waittime += interval;
value = script.Parent.SwayCFrame.Value;
if waittime >= timeout then
-- failed nothing to do but return here
return;
end
end
-- connect the render function
connection = game:GetService("RunService").RenderStepped:Connect(function()
-- rest of code ...
end)
end)