- Home /
Can you check a boolean in a coroutine?
I have one object checking for a coroutine in Update to return true, in which case it will detach itself from its parent.
But to me, it seems like a waste to be checking every single frame, as I don't expect the boolean to change that frequently. Is it possible to check in a coroutine? Or would it even matter? Is this even a noticeable impact in overhead?
My specific script is pretty simple:
public EnemyDeath enemyDeath;
void Start () {
enemyDeath = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyDeath>();
}
void Update(){
if(enemyDeath.enemyDead){
transform.parent = null;
}
Checking a single boolean will not break or make your frame rate. It should be okay to check it in Update().
Can you post your script, or an altered version of it to show what you mean?
From your description it sounds a bit like this could be handled by a delegate, ins$$anonymous$$d of the constant checking. But had to tell without details.
Oh if that's all you're doing then go ahead and check in the coroutine and set the parent to null in the coroutine.
Answer by AyAMrau · Sep 08, 2014 at 02:53 AM
Instead of constant checking you could use a delegate.
In the EnemyDeath script add:
public System.Action OnDeath;
And then in the same script, at the point where you set the enemyDead to true add:
If(OnDeath != null) // make sure something is assigned
{
OnDeath();
}
Then in the script you shown in start:
GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyDeath>().OnDeath += OnEnemyDeath;
And in the same script as a method:
private void OnEnemyDeath()
{
transform.parent = null;
GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyDeath>().OnDeath -= OnEnemyDeath;
}
This is a bit more typing, but gives you the knowledge about state change without constant checks, while still not forcing the EnemyDeath to know about other scripts.
Answer by Kiwasi · Sep 08, 2014 at 04:39 AM
One way to do this is properties.
private bool _enemyDead;
public bool enemyDead {
get {
return _enemyDead;
}
set {
// Take action here
_enemyDead = value;
}
}
Some thoughts on properties:
Using properties will add a method call to checking the bool, so it will be more expensive in terms of performance each time. But it will be cheaper then checking every frame.
Properties also tend to be set and forget. There is no code required to maintain them every frame. This works great if you trigger a property from a coroutine. Also useful for data validation.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162539im_/https://answers.unity.com/themes/thub/images/avi.jpg)