- Home /
The question is answered, right answer was accepted
Call a fuction only once on startup
Is there a way to call a fuction at game start? I can't use the Start() fuction of the script because it is used in multiple scenes, but I need to call a function when the game starts, that won't be called after every scene change.
Answer by Captain_Pineapple · May 29, 2018 at 09:29 AM
You could introduce a static variable in the given class. Let's call it public static bool initDone = false;
; When you do your init you should check for the following:
public void Start(){
if(initDone == false)
{
initDone = true;
//Do your stuff once here and it should only happen once in a game.
}
}
Hope this helps or points you in the right direction.
But when I load another scene that uses the same script, initDone will be false again.
Did you actually check this?
I thought the default is only applied when first initializing the variable. Anyway in case you are right you can introduce a class for solving your issue. $$anonymous$$ake that class static and let it only handle this variable, nothing else. Don't forget to NOT derive it from monobehaviour. Then you can check from any script at any given time if the first init was already done.
You're right, that works :) Thank you very much. I should've checked it before answering.