I asked this question to the forums but did not receive an answer.
I am calling a function from the void Update function.
Inside of the function I am trying to add a number to a variable, something like this:
myMoney = myMoney + 5.0m;
Because the function is being called from within the void Update function it keeps updating for every frame and the following happens.
Let’s say that the variable myMoney contains a 5.0m.
Within the function I have the following code.
myMoney = myMoney + 5
I expect to see a 10 but instead, the function runs over and over until I press a key to get me out of the function and I wind up with something like 250 or whatever instead of 10.
I tried to use a Boolean to do this operation such as:
public bool bolStopAdding;
Initialize bolStopAdding before calling the function to false.
In the function I have this code.
if (bolStopAdding == false) {
myMoney = myMoney + 5.0m;
bolStopAdding = true;
}
For some reason this does not work.
Any suggestions would be welcome.
Thank you,
magicscreen
asterling@nj.rr.com
If you do that only once on script start then I see no reason to not use Start() function instead. If you do that on some event (like button click) then you should either do that in that particular event or if that event is in some other script then set your “bolStopAdding” to false in that event and everything should work (considering the provided part of code only).
If that^ won’t help you then could you say what this means:“Initialize bolStopAdding before calling the function to false.”(e.g. how do you do that) and how and what is your “For some reason this does not work.”.
Also just FYI, note that you can shorten myMoney = myMoney + 5.0m; to myMoney += 5.0m; (that won’t grant any performance benefits though).
P.S. Also NOTE that your “bolStopAdding” should be outside the function (e.g. in class itself).
P.P.S. Thought TBH, even if you set boolean to false from some other script I would still rather create separate function and call if from other script or increase “myMoney” from other script instead of checking your boolean every time in Update function, maybe you have a valid reason to do so (and it will work) but from what you’ve provided I see none. So if you have no valid reason to use Update I’d move away from it, if you’ll have few hundreds or thousands of such if checks that runs only once it will noticeably affect performance.
Thanks for your help. I fixed the issue:
[Resolved] Thanks for your reply. I resolved my issue.
Instead of myMoney = myMoney + 5.00m; I did the following:
if (Input.GetKeyDown(KeyCode.M)) {myMoney = myMoney + 5.00m; myState = States.money;}
My issue was the line above my fix kept updating the myMoney field in an endless loop.
dterbeest gave me the hint.