I’ve been trying to get my character to repeat this line of dialogue:
“We need 24 more bombs.”
Each time this code is run, I get 0 instead of 24, or any other number. I used a remoteEvent to get the sum of two intValues instead of doing it client side, and I made a function that gets the sum once returned. The sum is fine until having to set the variable’s value to the sum.
local function checkBombs()
requestBombs:FireServer()
repeat RunService.Heartbeat:Wait() until requestBombs.OnClientEvent
requestBombs.OnClientEvent:Connect(function(bombNum)
explosives = bombNum
print(explosives)
end)
end
explosives is 24 after this is ran. But for some reason, when the dialogue is ran, explosion is 0. Here’s the code of the current line I’m trying to run.
"We need "..explosives.." more bombs.", -- bombCheck, progress (101)
Hmm… I can’t see anything wrong with your code, other than the unnecessary repeat RunService.Heartbeat:Wait() until requestBombs.OnClientEvent.
How about instead of sending the amount of bombs left everytime to the client, you send the amount of bombs they already have to the client, and then the client does the math?
Improvements
Also, you have a performance flaw in your client code. Everytime checkBombs() is called (which im guessing is very often), you make a new connection which should be closed after a response, but isn’t.
Additionally, it’d be better if instead of setting a global variable called explosives to the bomb number, you could just return the value instead.
Here is your function with the new improvements:
local function checkBombs()
requestBombs:FireServer()
local connection
connection = requestBombs.OnClientEvent:Connect(function(bombNum)
connection:Disconnect() -- disconnect connection to prevent memory and performance problems
print(explosives) -- print, just like you wanted :)
return bombNum -- return instead of setting global variable
end)
end
The code runs once the character picks a dialogue option, and once for the line of npc dialogue. I’ve also tried returning the value but I did do it differently than you, so I’ll try what you did out. Thanks!
Whoops… forgot about something. It takes a while before a response is received from the server.
How many times do you use this function? If you only use it once or twice it’s better to just put this code in the same thread. Here:
requestBombs:FireServer()
local connection
connection = requestBombs.OnClientEvent:Connect(function(bombNum)
connection:Disconnect() -- disconnect connection to prevent memory and performance problems
print(explosives) -- print, just like you wanted :)
-- your code here!
print("We need "..bombNum.." more bombs.")
end)
I have heard of something called a RemoteFunction which would be better to use than remoteEvents but I have never used it so you might want to read about it more here: RemoteFunction | Documentation - Roblox Creator Hub