Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can I change values of variables after the variable is created?

Asked by 3 years ago

Im making a script so that if a certain variable is true and the player has clicked their mouse that it will play an animation. The animation is working, but when i change the value of a variable in the script, it doesnt change it.

local userinputservice = game:GetService("UserInputService")
local animationPlaying = false
local animationBegan = game.ReplicatedStorage.animationBegan

animationBegan.OnServerEvent:Connect(function(player)
local humanoid = player.Character.Humanoid
local animation = humanoid:LoadAnimation(script.animation)

        userinputservice.InputBegan:Connect(function(input)
                if input.UserInputType == Enum.UserInputType.MouseButton1 then
                        animationPlaying = true

                        animation:Play()
                        wait(1)

                        animationPlaying = false
                end
         end)
if animationPlaying == true then
        print("animation is Playing")
end

When I run that script and I click, it never prints "animation is Playing" meaning that the value wasn't changed. How do I change the value of a variable after I create it?

1 answer

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

UserInputService is not available on the server, you have to use it on the client instead because it is designed to detect user input from one player as the server oversees all players and itself.

Solution? Convert your script into local script and skip the OnServerEvent event/function connection.

Result:

local userinputservice = game:GetService("UserInputService")
local animationPlaying = false
local animationBegan = game.ReplicatedStorage.animationBegan

local humanoid = player.Character.Humanoid
local animation = humanoid:LoadAnimation(script.animation)

userinputservice.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        animationPlaying = true

        animation:Play()
        wait(1)

        animationPlaying = false
    end
end)

Note: I removed the 'if statement' that checked if the animation was playing or not, you can add this yourself if you want back.

If you experience this error: "Humanoid is not a descendant of Game Model", then replace the humanoid variable with this:

local humanoid = player.Character:WaitForChild("Humanoid")

while humanoid and not humanoid:IsDescendantOf(workspace) do
    humanoid.AncestryChanged:Wait()
end
0
It worked! Thanks packayee 13 — 3y
Ad

Answer this question