im trying to make an infection system and it doesnt work, i made it into a local function and added math.random to pick a random number and if it picks a certain number it calls the local function.
it prints the number but the local function doesnt work and it doesnt seem there are any errors in the output, please help me fix this. code:
local rs = game:GetService("RunService")
local soundfolder = script.SoundFolder:GetChildren()
local debounce = true
local function infect()
local last = nil
for i,v in pairs(game.Players:GetChildren()) do
if last == nil then
last = v
end
if last.Character and v.Character then
if last and last~= v then
local dist = (last.Character.HumanoidRootPart.Position-v.Character.HumanoidRootPart.Position).magnitude
if dist <= 5 then
print("The player "..v.Name.." is close to "..last.Name)
end
last = v
end
end
end
end
local playerschildren = game.Players:GetChildren()
game.ReplicatedStorage.characteradded.OnServerEvent:Connect(function(plr)
local randomnum2 = math.random(1,2)
print(randomnum2)
if randomnum2 == 2 then
infect()
end
end)
Have you done checks to see if your local function is even running, the issue seems to be the logic of your code, from reading you’re defining last as the character of that player, and then you’re doing "if last and last ~= v". This means the conditional statement won’t run since you defined last as the character model, which is also what the v variable is. You should be saving the position not the model. e.g last = v.Position and then you would do local dist = (last - v.Character.HRP.Position).magnitude
you have defined v to be the player, however, the player is not a physical object and has no position. This means you should do v.Character.HumanoidRootPart.Position to reference the position of the player, because the humanoidrootpart is a part in the player that has a position that changes with the movement of the player.
Also, how you define last may need to change. From what I see, last has been defined as v, which is the player object and not the position of the character of the player.