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

Spawn function not working as espected?

Asked by
Necro_las 412 Moderation Voter
3 years ago
Edited 3 years ago

Hello, im scripting an NPC. After setting the pathfinding functions, i've connected it in a While loop inside a spawn. There are 2 loops playing in spawns, one for constantly checking if there is a player neaby, other checking if the character is attacking someone or it can move around for a random position.

To know when the NPC is attacking or not, I crate this variable called "attacking". It is suposed to be set to 5 in the second loop everywhen a player is detected nearby, and then the first loop stops moving the NPC to random positions and wait until the attacking goes down from 5 to 0. With this, i want the NPC to remain in "attacking" state for 5 seconds after it stops detecting a player, and want it not to move randomly while attacking. The second loop though keeps moving the NPC to the nearest sensed player constantly.

The problem is: the attacking variable seems to stop being set to 5 when the loop "while attacking > 0 do" is running. I dont want this to happen and dont expect it sinse they are in 2 separate threads. When printing the attacking variable constantly, it starts to go down until 0 instead of keep constantly in 5 while following the player, and when it reaches 0, it goes to 5 again. Weird. With a print right after "attacking = 5" i checked that it really sets to 5 on that loop, but then looks like that 5 does not became the global variable "attacking", the output goes (nearly) like this:

5, 
4.9, 
5, 
4.8, 
5, 
4.7, 
5, 
4.6, 
5, 
4.5

The code:

local attacking = 0
ViewAngle = 90

spawn(function()
    while wait(3) do
        if attacking <= 0 then
            followPath(center + Vector3.new(math.random(-30,30), 0 , math.random(-30,30)))
        else
            while attacking > 0 do
                print(attacking)
                attacking = attacking - wait()
            end
            ViewAngle = 90
        end
    end
end)

spawn(function()
    while wait() do
        local plrs = GetPlayersInFront(Root, ViewAngle, 40)
        if plrs then
            closer = getCloser(plrs)
            if closer then
                attacking = 5
                print(attacking)
                ViewAngle = 360
                followPath(closer.Position)
            end
        end
    end
end)
0
I'm pretty sure you can't change a variable across threads Spjureeedd 385 — 3y

1 answer

Log in to vote
0
Answered by
Necro_las 412 Moderation Voter
3 years ago

I found the answer, for an unknown reason it was that attacking = attacking - wait() that was creating the bug

Ad

Answer this question