我在C中编写了一个可以在多个旧平台上运行的游戏引擎,例如Sega Saturn和PS1。不过,我遇到过一个小问题。游戏有一个主循环,从中调用所有其他函数。这意味着在没有涉及状态的情况下,只调用一次函数非常困难。所以,我需要知道最好的方法。我将展示一个如何设置的简短示例:
mainloop() //This function repeats forever
{
myFunc1(); //Therefore, this function also repeats forever.
}
myFunc1() //Subsequent, gameplay related function
{
if(myThing == 9){ //This thing is gonna equal 9 for quite a while, so that means the fucntion below will also be called like a bunch. But we don't want it to!
runFuncOnce(); //Run this function only one time
}
}
runFuncOnce() //I only want this function to do stuff one time until the next time it gets called!
{
//Some examples of things you'd only want to do one time:
PlayASound(MySound);
ResetAnimation(MyAnimation); //Set an animation back to its first frame
myVariable = 5; //Set this variable to whatever, but only once!
printf("Hey, you did a thing. Good job! If you're lucky you won't see this text like 8 billion times in a row")
}
当然,你不会想在同一个功能中做这些事情,但你明白了。有一些愚蠢的方法可以做到这一点,但我试图以最干净,最快的方式做到这一点。我不想谈论我做它的方式,因为人们很可能会关注我之前尝试过的方式,并尝试解决这个问题。 。给我新鲜的想法!相信我,我之前做过的方式是愚蠢和缓慢的。这就是我在这里的原因!
答案 0 :(得分:1)
您可以使用静态变量。
myFunc1() //Subsequent, gameplay related function
{
static bool runOnlyOnce = false;
if(myThing == 9) { //This thing is gonna equal 9 for quite a while, so that means the function below will also be called like a bunch. But we don't want it to!
if (runOnlyOnce == false) {
runFuncOnce(); //Run this function only one time
runOnlyOnce = true;
}
}
}
静态变量值在函数调用之间持续存在。因此,当下次调用myFunc1()
时,它会找到runOnlyOnce
变量true
的值,并且不会再次调用runFunOnce()
。