while loop wont work inside of the other while loop - lua

I'm scripting in roblox lua and when I try to put a while loop in the first it messes up the first sequence of code can someone give me hand in fixing this?
The problem is that when the humanoid makes it to tar2 he stops there and wont move I want him to continue running to the points but while also having it so where if a actual person comes by then he runs after him instead.
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local plr = game.Players:GetChildren()
local tar1 = game.Workspace.tar1
local tar2 = game.Workspace.tar2
local tar3 = game.Workspace.tar3
local tar4 = game.Workspace.tar4
local pos = {tar1, tar2, tar3, tar4}
local char = script.Parent
local Hum = char.Humanoid
torso = char.Torso
GoTo = 0
while true do
wait(1)
if GoTo == 0 then
Hum:MoveTo(pos[1].Position)
end
if (torso.Position - pos[1].Position).magnitude < 5 then
GoTo = 1
end
if GoTo == 1 then
Hum:MoveTo(pos[2].Position)
end
if (torso.Position - pos[2].Position).magnitude < 5 then
GoTo = 2
end
if GoTo == 2 then
Hum:MoveTo(pos[3].Position)
Goto = 3
end
if (torso.Position - pos[3].Position).magnitude < 5 then
GoTo = 4
end
if GoTo == 5 then
Hum:MoveTo(pos[4].Position)
end
while true do
wait(0.1)
plrs = game.Players:GetChildren()
for i,plr in ipairs(plrs) do
if plr.Character ~= nil then
tor = plr.Character.Torso
if (torso.Position-tor.Position).magnitude <= 5 then
GoTo = 0
Hum:MoveTo(tor.Position)
end
end
end
end
end

Coroutines! Coroutines are the bombdiggety. They let you do multiple while loops at once in a single script.
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local plr = game.Players:GetChildren()
local tar1 = game.Workspace.tar1
local tar2 = game.Workspace.tar2
local tar3 = game.Workspace.tar3
local tar4 = game.Workspace.tar4
local pos = {tar1, tar2, tar3, tar4}
local char = script.Parent
local Hum = char.Humanoid
torso = char.Torso
GoTo = 1
function normalCor() -- run around
while true do
wait(1)
for i=1, 4 do
if GoTo == i then
Hum:MoveTo(pos[i].Position)
end
if (torso.Position - pos[i].Position).magnitude < 5 then
GoTo = GoTo + 1
if GoTo == 5 then
GoTo = 1
end
--[[
The above _can_ be done in a single statement:
"GoTo = (GoTo+1)%4+1"
"a % 4" gets the remainder of a / 4 ]]
end
end
end
end
cr = coroutine.create(normalCor)
coroutine.resume(cr) -- this lets you do two while loops at the same time.
function aggroCor() -- when a player is nearby
while true do
wait(0.1)
plrs = game.Players:GetChildren()
for i,plr in ipairs(plrs) do
if plr.Character ~= nil then
tor = plr.Character.Torso
if (torso.Position-tor.Position).magnitude <= 5 then
GoTo = 0
Hum:MoveTo(tor.Position)
end
end
end
end
end
cr = coroutine.create(aggroCor)
coroutine.resume(cr)
Roblox has the syntax spawn(aggroCor) that you can play around with too,
if coroutine.whatever seems like too much work.

Related

Issue With Moving Character Models In Roblox

I am currently in the process of making a game known as Elf Tycoon. This game involves the player buying elves, (dummy character rigs as placeholders). These characters are then aligned in rows of 8, going on forever. I am having an issue with the system. It seems that every floor apart from the first has its first elf slightly lower than the others. Attached is a screenshot of the issue, and the code is below.
local elvesFolder = script.Parent.Elves
local elfValues = script.Parent.ElfValues
local tycoonLevel2 = script.Parent:FindFirstChild("Tycoon Level 2")
local repStorage = game:GetService("ReplicatedStorage")
local tycoonRoof = script.Parent["Tycoon Roof"]
local currentNumberOfFloors = 1
local currentLevel = 2
local elves = 60
local remainingElves = 60
local number_of_floors = math.floor(elves/9)-1
local tierOneElf = script.Parent.Elves:FindFirstChild("T1 Elf")
local function ResetTycoon()
for i,v in pairs(elvesFolder:GetChildren()) do
v:Destroy()
end
for i,v in pairs(script.Parent:GetChildren()) do
if v.Name == "New Tycoon Level" or v.Name == "Tycoon Level 2" then
v:Destroy()
end
end
end
local function ResetElves()
remainingElves = elves
number_of_floors = math.floor(elves/9)+1
if elves <= 9 then
number_of_floors = 1
end
if number_of_floors >= 2 then
local levelTwo = repStorage:FindFirstChild("Tycoon ".. script.Parent.Name:split(" ")[2] .." Level 2")
if levelTwo then
local newLevel = levelTwo:Clone()
newLevel.Parent = script.Parent
newLevel.Name = "Tycoon Level 2"
end
end
for i = 1,number_of_floors do
if i >= 3 then
local newFloor = tycoonLevel2:Clone()
newFloor.Name = "New Tycoon Level"
newFloor.Parent = script.Parent
for a,b in pairs(newFloor:GetDescendants()) do
if b:IsA("Part") or b:IsA("MeshPart") then
b.Position += Vector3.new(0,7.9*(i-2),0)
end
end
end
for a,b in pairs(tycoonRoof:GetDescendants()) do
if b:IsA("Part") or b:IsA("BasePart") then
b.Position = Vector3.new(b.Position.X,28+7.9*(i-1),b.Position.Z)
end
end
for j = 1,9 do
if j == 1 then
local newElf = repStorage["Tycoon ".. script.Parent.Name:split(" ")[2] .." T1 Elf"]:Clone()
newElf.Name = "T1 Elf"
newElf.Parent = elvesFolder
if i ~= 1 then
for a,b in pairs(newElf:GetDescendants()) do
if b:IsA("Part") or b:IsA("BasePart") then
b.Position += Vector3.new(0,7.9*(i-1),0)
end
end
end
remainingElves -= 1
else
if remainingElves >= 1 then
local newestElf = nil
for a,b in pairs(elvesFolder:GetChildren()) do
newestElf = b
end
local newElf = newestElf:Clone()
newElf.Name = "T1 Elf"
newElf.Parent = elvesFolder
newElf:MoveTo(Vector3.new(newElf.PrimaryPart.Position.X,newElf.PrimaryPart.Position.Y,newElf.PrimaryPart.Position.Z)+(-newElf.PrimaryPart.CFrame.RightVector*6))
end
remainingElves -= 1
end
end
end
end
Note: This is only the first function in the script. This is where the issue would be occurring. Thanks for any help that you can provide!
Here is that screenshot. The expected result is to have all of the elves aligned properly for each floor:

found out of script not updating - roblox lua

I am trying to make it so the GUI updates every time a player collects an item to show how many items they have collected. it works very well, but it only updates when the player leaves and rejoins. Any ideas??
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local catscollected = player:WaitForChild("catsCollected")
Cats_Found_Out_Of = 0
if catscollected:FindFirstChild("sleeping cat") then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
if catscollected:FindFirstChild("fire cat") then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
end
end
while true do
script.Parent.Text = Cats_Found_Out_Of.." / 3 Found"
end
It is because of not putting an if statement into the while loop.
Explanation:
Don't use while true do, instead of this use while wait(0.1) do so it will not lag the whole game on client side
It will run only on join and leave because you haven't put the if statement into the while loop. You can either change it to the function or put into the while loop as a code.
Your code should now look like this:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local catscollected = player:WaitForChild("catsCollected")
while wait(0.1) do
Cats_Found_Out_Of = 0
for _, v in pairs(catscollected:GetChildren()) do
if v.Name == "sleeping cat" or v.Name == "fire cat" then
Cats_Found_Out_Of = Cats_Found_Out_Of + 1
end
end
script.Parent.Text = Cats_Found_Out_Of.." / 3 Found"
end

Part doesn't gives damage with Touched Event

I made a code for my game, it's a type of punch, with a hitbox made with a common Part. I proggrammed to the part give some damage according with the player strenght. It didn't work, no errors in output. Code here:
local rep = game:GetService("ReplicatedStorage")
local debounceDMG = true
rep.Combate.Soco.OnServerEvent:Connect(function(plr)
local math = math.random(1,2)
local char = plr.Character or plr.CharacterAdded:Wait()
local Humanoid = char.Humanoid
local lanim = char.Humanoid:LoadAnimation(script.Left)
local lanim1 = char.Humanoid:LoadAnimation(script.Animation)
local hitbox = Instance.new("Part")
hitbox.Parent = workspace
hitbox.Transparency = 1
hitbox.Anchored = true
hitbox.CanCollide = false
hitbox.Size = Vector3.new(2.5,2.5,2.5)
game:GetService("RunService").Heartbeat:Connect(function()
if math == 2 then
hitbox.Position = char.LeftHand.Position
elseif math == 1 then
hitbox.Position = char.RightHand.Position
end
end)
if math == 2 then
lanim:Play()
elseif math == 1 then
lanim1:Play()
end
hitbox.Touched:Connect(function(hit)
local h = hit.Parent:FindFirstChild("Humanoid")
if h then
if h ~= Humanoid and debounceDMG then
debounceDMG = false
h.Health -= plr.Data.Forca.Value + 5
task.wait(.5)
debounceDMG = true
end
end
end)
task.wait(.3)
hitbox:Destroy()
end)
You use "if h~=Humanoid" will always look for Non Humanoid, your code will never reach the Health deduction. Try to code below if working
hitbox.Touched:Connect(function(hit)
local h = hit.Parent:FindFirstChild("Humanoid")
if h ~= nil and debounceDMG then
debounceDMG = false
h.Health -= plr.Data.Forca.Value + 5
task.wait(.5)
debounceDMG = true
end
end)

Lua error attempt to index nil value while checking if player has the correct amount of a item

This script allows people to produce meth, starting production will succeed when you have the right amount of objects in your inventory.
Only when you don't have the right amount you should get a notification and you don't get that notification..
Following error pops up: SCRIPT ERROR: #ns-meth/server.lua:18: Attempt to index a nil value.
Code:
RSCore = nil
Citizen.CreateThread(function()
while RSCore == nil do
TriggerEvent('RSCore:GetObject', function(obj) RSCore = obj end)
Citizen.Wait(0)
end
end)
RegisterServerEvent('RSCore_methcar:start')
AddEventHandler('RSCore_methcar:start', function()
local src = source
local Player = RSCore.Functions.GetPlayer(src)
local amount = 0
if Player.Functions.GetItemByName('acetone').amount >= 5 and Player.Functions.GetItemByName('lithium').amount >= 2 and Player.Functions.GetItemByName('methlab').amount >= 1 then
TriggerClientEvent('RSCore_methcar:startprod', src)
Player.Functions.RemoveItem('acetone', 5)
Player.Functions.RemoveItem('lithium', 2)
else
if Player.Functions.GetItemByName('acetone').amount <= 4 and Player.Functions.GetItemByName('lithium').amount <= 1 and Player.Functions.GetItemByName('methlab').amount <= 0 then
RSCore.Functions.Notify("Je hebt niet de juiste benodigdheden!", "error")
end
end
end)
RegisterServerEvent('RSCore_methcar:stopf')
AddEventHandler('RSCore_methcar:stopf', function(id)
local src = source
local Players = RSCore.GetPlayers()
local Player = RSCore.Functions.GetPlayer(src)
for i=1, #Players, 1 do
TriggerClientEvent('RSCore_methcar:stopfreeze', Players[i], id)
end
end)
RegisterServerEvent('RSCore_methcar:make')
AddEventHandler('RSCore_methcar:make', function(posx,posy,posz)
local src = source
local Player = RSCore.Functions.GetPlayer(src)
if Player.Functions.GetItemByName('methlab').amount >= 1 then
local Players = RSCore.Functions.GetPlayer(src)
for i=1, #Players, 1 do
TriggerClientEvent('RSCore_methcar:smoke',Players[i],posx,posy,posz, 'a')
end
else
TriggerClientEvent('RSCore_methcar:stop', src)
end
end)
RegisterServerEvent('RSCore_methcar:finish')
AddEventHandler('RSCore_methcar:finish', function(qualtiy)
local src = source
local Player = RSCore.Functions.GetPlayer(src)
print(qualtiy)
local rnd = math.random(-5, 5)
TriggerEvent('KLevels:addXP', src, 20)
Player.Functions.AddItem('meth', math.floor(qualtiy / 2) + rnd)
end)
RegisterServerEvent('RSCore_methcar:blow')
AddEventHandler('RSCore_methcar:blow', function(posx, posy, posz)
local src = source
local Players = RSCore.GetPlayers()
local Player = RSCore.Functions.GetPlayer(src)
for i=1, #Players, 1 do
TriggerClientEvent('RSCore_methcar:blowup', Players[i],posx, posy, posz)
end
Player.removeInventoryItem('methlab', 1)
end)
RegisterServerEvent('ns-meth:server:callCops')
AddEventHandler('ns-meth:server:callCops', function(streetLabel, coords)
local msg = "Er is een verdachte situatie op "..streetLabel..", mogelijks drugs productie."
local alertData = {
title = "Verdachte situatie",
coords = {x = coords.x, y = coords.y, z = coords.z},
description = msg
}
for k, v in pairs(RSCore.Functions.GetPlayers()) do
local Player = RSCore.Functions.GetPlayer(v)
if Player ~= nil then
if (Player.PlayerData.job.name == "police" and Player.PlayerData.job.onduty) then
TriggerClientEvent("ns-meth:client:robberyCall", Player.PlayerData.source, msg, streetLabel, coords)
TriggerClientEvent("rs-phone:client:addPoliceAlert", Player.PlayerData.source, alertData)
end
end
end
end)

ROBLOX - Why is this fly script working only in the Studio?

I really need help..
I have this code for fly, as a backpack item:
Name = "Fly"
pi = 3.141592653589793238462643383279502884197163993751
a = 0
s = 0
ndist = 13
rs = 0.025
siz = Vector3.new(1, 1, 1)
form = 0
flow = {}
function CFC(P1,P2)
local Place0 = CFrame.new(P1.CFrame.x,P1.CFrame.y,P1.CFrame.z)
local Place1 = P2.Position
P1.Size = Vector3.new(P1.Size.x,P1.Size.y,(Place0.p - Place1).magnitude)
P1.CFrame = CFrame.new((Place0.p + Place1)/2,Place0.p)
end
function checktable(table, parentneeded)
local i
local t = {}
for i = 1, #table do
if table[i] ~= nil then
if string.lower(type(table[i])) == "userdata" then
if parentneeded == true then
if table[i].Parent ~= nil then
t[#t + 1] = table[i]
end
else
t[#t + 1] = table[i]
end
end
end
end
return t
end
if script.Parent.Name ~= Name then
User = game:service("Players").Nineza
HB = Instance.new("HopperBin")
HB.Name = Name
HB.Parent = User.StarterGear
script.Parent = HB
User.Character:BreakJoints()
end
speed = 50
script.Parent.Selected:connect(function(mar)
s = 1
torso = script.Parent.Parent.Parent.Character.Torso
LeftShoulder = torso["Left Shoulder"]
RightShoulder = torso["Right Shoulder"]
LeftHip = torso["Left Hip"]
RightHip = torso["Right Hip"]
human = script.Parent.Parent.Parent.Character.Humanoid
bv = Instance.new("BodyVelocity")
bv.maxForce = Vector3.new(0,math.huge,0)
bv.velocity = Vector3.new(0,0,0)
bv.Parent = torso
bg = Instance.new("BodyGyro")
bg.maxTorque = Vector3.new(0,0,0)
bg.Parent = torso
connection = mar.Button1Down:connect(function()
a = 1
bv.maxForce = Vector3.new(math.huge,math.huge,math.huge)
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
moveconnect = mar.Move:connect(function()
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
end)
upconnect = mar.Button1Up:connect(function()
a = 0
moveconnect:disconnect()
upconnect:disconnect()
bv.velocity = Vector3.new(0,0,0)
bv.maxForce = Vector3.new(0,math.huge,0)
torso.Velocity = Vector3.new(0,0,0)
bg.cframe = CFrame.new(torso.Position,torso.Position + Vector3.new(torso.CFrame.lookVector.x,0,torso.CFrame.lookVector.z))
wait(1)
end)
end)
while s == 1 do
wait(0.02)
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
if a == 1 then
flow[#flow + 1] = Instance.new("Part")
local p = flow[#flow]
p.formFactor = form
p.Size = siz
p.Anchored = true
p.CanCollide = false
p.TopSurface = 0
p.BottomSurface = 0
if #flow - 1 > 0 then
local pr = flow[#flow - 1]
p.Position = torso.Position - torso.Velocity/ndist
CFC(p, pr)
else
p.CFrame = CFrame.new(torso.Position - torso.Velocity/ndist, torso.CFrame.lookVector)
end
p.BrickColor = BrickColor.new("Cyan")
p.Transparency = 1
p.Parent = torso
local marm = Instance.new("BlockMesh")
marm.Scale = Vector3.new(1.9, 0.9, 1.725)
marm.Parent = p
local amplitude
local frequency
amplitude = pi
desiredAngle = amplitude
RightShoulder.MaxVelocity = 0.4
LeftShoulder.MaxVelocity = 0.4
RightHip.MaxVelocity = pi/10
LeftHip.MaxVelocity = pi/10
RightShoulder.DesiredAngle = desiredAngle
LeftShoulder.DesiredAngle = -desiredAngle
RightHip.DesiredAngle = 0
LeftHip.DesiredAngle = 0
end
end
end)
script.Parent.Deselected:connect(function()
a = 0
s = 0
bv:remove()
bg:remove()
if connection ~= nil then
connection:disconnect()
end
if moveconnect ~= nil then
moveconnect:disconnect()
end
if upconnect ~= nil then
upconnect:disconnect()
end
while s == 0 do
wait()
if #flow > 0 then
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
end
end
end)
while true do
wait()
if s == 1 then
return
end
end
script:remove()
The script is in a HopperBin Object in the game's StarterPack Folder.
Now if you try it on your own, you'll see that it will work, BUT if you publish the game, play it via ROBLOX(not the studio) and try to use the item, you won't fly.
Any ideas why?
It's been a long time since I haven't played ROBLOX, so my answer might be inaccurate.
First, you need to understand the difference between a Script and a Localscript. In a nutshell, a script runs server-side whereas a Localscript runs client-side. Your fly script is expected to run on a player's client, thus you have to use a Localscript.
Your regular script works in build-mode because scripts are run on your client, and thus are considered as Localscripts. When you publish your game and play it, your computer doesn't work as a server anymore, but as a client.
In addition to this, as you use a localscript, you may have to change the following line :
-- gets the client (local player) on which the script is running
User = Game:GetService("Players").LocalPlayer
Also, avoid relative paths such as script.Parent.Parent.Parent..... You want to get the client's torso, so just use your User variable as per : User.Character.Torso. Do the same for the character's Humanoid object.
I think it's because the time to load not existing try this at line1:
repeat wait() until game.Players.LocalPlayer.Character

Resources