- Home /
Do something when health is below X
Hi, I want to do something when the health of the character is below X. I know the easiest and the common way is
void Update(){
if(health<X) DoSomething();
}
But it is highly inefficient since it will check the health in every frame. If game lasts hours, imagine the wasted processing power. If I need to check many things, there will be many if statements in the Update and code will be messy too. Also if DoSomething() will be used for once (like give health bonus for once) in the game, there will be an useless always-false if statement in every frame during the game after that. Are there any other ways (like interrupts) to do this?
Answer by Hexer · Jul 25, 2015 at 08:59 AM
1 line of code with an if-statement will not highly affect your preformance on the long run. The line of codes that do affect your preformance if used too much are.
*GameObject.Find
*GameObject.FindWithTag (not as expensive as .Find but with alot of tags still troublesome)
*Resources.Load (never use this, it is uber slow. surely for mobile devices)
*Debug.Log (Get rid of this line of code when you are done making your game)
Next to code, the most important is to get the polycount(verts and tris) of your scene as low as possible. And don't make too much use of the light tools in Unity.
That all said, your method is perfectly fine.
EDIT : You can also use InvokeRepeating
void Start(){
InvokeRepeating("Brackets",0.1f,1.0f);
}
void Brackets(){
if(health >= 0){
Application.LoadLevel(0);
}
}
This is like the Update function where you can change the parameters to your liking.
Answer by ian_sorbello · Jul 25, 2015 at 09:02 AM
You need to use CoRoutines. http://docs.unity3d.com/Manual/Coroutines.html
So instead of the update function, do your checking in a routine that executes much less frequently.
This could also sort out the need for the "only once" scenario:
using System;
using System.Collections;
using UnityEngine;
public class BonusCheck : MonoBehaviour {
public float delay = 0.1f; // Run every 100ms.
private int points = 0;
// Use this for initialization
void Start () {
StartCoroutine (CheckForBonus ());
}
// Update is called once per frame
void Update () {
}
IEnumerator CheckForBonus() {
bool bonusAwarded = false;
while(!bonusAwarded) {
// Points greater than 200?
if(points > 200) {
AwardBonus();
bonusAwarded = true;
}
yield return new WaitForSeconds(delay);
}
}
private void AwardBonus() {
// Do award
}
}