Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

why the function does not activate?

I created a script that generates apples on trees. I also created an extra function that stops the spawn of apples if it reaches ten apples on the map. Okay so far ... the problem is that the function that checks how many apples on the map is not activating, does anyone know why? script:

wait(game.Players.PlayerAdded)
verdade = false
applevalue = game.Workspace.appleintvalue
applevalue.Value = 0
applescripton = true

function applecheck ()
	while true do
		wait(0.5)
		print('checando')
		if applevalue.Value ~= 3 then
			applescripton = true
		end
	if applevalue.Value == 3 then
		applescripton = false
	end
	end
end


function spawnapple ()
while applescripton == true do
	wait(math.random(1,10))
local apple = game.Workspace.apple:Clone()
apple.Parent = workspace

local arvore = game.Workspace.arvores:GetChildren()
local applaspawn = arvore[math.random(1, #arvore)]
local tronco = applaspawn:FindFirstChild('tronco1')
apple.CFrame = tronco.CFrame * CFrame.new(math.random(-6,6),8,math.random(-6,6))
print(applaspawn)

applevalue.Value = applevalue.Value + 1
print(applevalue.Value)
end
end

spawnapple()
applecheck()

if you find any errors, could you explain to me why this is happening and give me some tips on?

2 answers

✓ Accepted answer

Ah I see! The issue is; When a function is called, the code will only run the next line when something is returned. What you need to do is use the spawn() function. This will take a function as an argument and what it does is call a function without pausing the code, thus when you call spawn(spawnapple) it will continue running and proceed to run applecheck().

Here:

spawn(spawnapple)
spawn(applecheck)

4 comments

1

Don't use spawn. Use coroutine.wrap(spawnapple)()

0

^^ Note, coroutine can be hard to explain to new programmers, especially ones such as the one asking the question, there is no real problem in using spawn(). I find it quite fine to use both spawn() and coroutine.wrap() if I'm not worried about time.

0

the more you use spawn for your functions, the longer it takes to run

0

oh thanks programmerhere and sebgamingkid

just a helpful hit regarding your if statement; you can simplify it to

if applevalue.Value ~= 3 then
	applescripton = true
else
	applescripton = false
end

by using an "else". Instead of using 2 if statements for the same thing.

11	        if applevalue.Value ~= 3 then
12	            applescripton = true
13	        end
14	    if applevalue.Value == 3 then
15	        applescripton = false

1 comment

0

or you can do applescripton = applevalue.Value ~= 3 and true or false ;)

This discussion is preserved as it was. New answers, comments, and votes are closed.