- Home /
Where is the best place to use delegate call back without calling it in Update function?
I know how delegates work in general. What I don't understand, if I am going to use delegates to fire events instead of checking on the continuously in the update function. Where is the best place to call them? I am going to give an example in my real time strategy game. I have an army and everytime one of my units dies, a sound plays says "Unit has been eliminated" I created the function that plays the audio and subscribed to the onUnitDies(). What I don't understand where should I be using the call back? If I put it in the update function, isn't it as the same as just checking if the unit died in the update and then play the audio if the player died? whats the benefit then? If I used it in the Start function() its gonna be called only once. I need it to be called every time something happens. Not in the update and not in the start. How is that?
Answer by Hellium · Jan 29, 2019 at 07:45 PM
Without precise code of what you have so far, it is difficult to tell you if you understood the concept of events correctly.
Supposing you have two entities, a UnitsSpawner
spawning Units
. The latter will send an event when it dies and the UnitsSpawner
will be automatically warned that a spawned unit has died and call the appropriate function, without the need to poll the condition if( unit.hasDied )
public class Unit : MonoBehaviour
{
public event System.Action<Unit> OnDeath;
private int health;
public bool Dead { get ; private set ; }
public void Hurt( int damages )
{
if( Dead ) return ;
health = Mathf.Max( health - damages, 0 );
if( health == 0 )
{
Dead = true;
if( OnDeath != null )
OnDeath( this );
Destroy( gameObject );
}
}
}
public class UnitsSpawner : MonoBehaviour
{
public Unit UnitPrefab;
private void SpawnUnit()
{
Unit instance = Instantiate( UnitPrefab );
instance.OnDeath += OnUnitDied;
}
private void OnUnitDied( Unit unit )
{
unit.OnDeath -= OnUnitDied;
Debug.Log( "The unit " + unit.name + " has died");
}
}