Reputation: 171
I have a variable that I need to check frequently when my game is running. To simplify this, the check is: if (score >= achievement1) {do something}
.
It seemed overkill to put this check in the Update()
function which is called every frame;
So instead, I call the InvokeRepeating
function in the Start ();
function:
InvokeRepeating ("checkscoreforachievement", 0f, 2f);
Is this smart or is there a better way doing this? End result should be that within a few seconds after achieving a certain score, the achievement is triggered.
The reason I'm asking is that there are a few more things I need to do regularly when my game is running, so I'll end up with quite a few of these processes. Wondering if that isn't too much of a resource drain. Can't find good documentation on this subject.
Upvotes: 2
Views: 484
Reputation: 125455
No, InvokeRepeating
is not better in this case.
It's not better because you are calling that function every 2 seconds which means that when score >= achievement1
evaluates to true
, it will take about 2 seconds to detect that. Also, InvokeRepeating
uses reflection which is slow. There is no advantage of using it here. Using the Update
function like you are currently doing it is totally fine.
A much more better solution than using the Update
function would be to check if score >= achievement1
only when score is changed with auto property.
public int achievement1 = 0;
private float _score;
public float score
{
get
{
return _score;
}
set
{
if (_score != value)
{
_score = value;
if (_score >= achievement1)
{
//Do something
}
}
}
}
This will only do the check when the score
variable is set or changed instead of every frame but the Update
code is fine.
Upvotes: 5
Reputation: 1884
Some other users have pointed this out similar things already, but essentially when the score is changed, call a function of your own to check. Don't invoke repeating or use update because honestly, it's just unnecessary to do it so infrequently or so frequently respectively.
Literally set it that when your score is incremented or decremented (changed in any way) you call the function to check.
You could also create an Array of achievements, and check the index before you even call the function to display/update the achievement:
if(arrayname[i] != "Unlocked"){
//Call function;
}
Upvotes: 0