- Home /
Question about subscribing to an event
I have a gameobject that's a door that opens when all the enemies are killed. My GameManager script has an event that's invoked when all the enemies are killed. My door script subscribes to this event, so when all the enemies are killed, the door opens. The way the door opens is via the transform.translate function. However, if you look at my code below, you can see why this doesn't work.
private void Start()
{
GameManager.Instance.OnAllEnemiesKilled += OpenDoor;
}
private void OpenDoor()
{
transform.Translate(Vector2.down * (_speed * Time.deltaTime));
}
private void OnDestroy()
{
GameManager.Instance.OnAllEnemiesKilled -= OpenDoor;
}
Transform.translate I guess has to run in update or fixedUpdate in order for the door to completely open (right now it only opens for one frame and then stops). But if I execute the transform.translate function inside of an update method, wouldn't that mean that I have to constantly check in the update whether or not all the enemies are killed? Aren't events better for that, because it avoids having constantly check for something? Can I have my cake and eat it too?
Answer by Priyanka-Rajwanshi · Apr 08, 2018 at 04:04 AM
@sean244 You can start a coroutine in OpenDoor() which would translate the door for you till a condition is met.
StartCoroutine (OpenDoorCoroutine());
IEnumerator OpenDoorCoroutine(){
while(!condition met)
{
yield return null;
transform.Translate(Vector2.down * (_speed * Time.deltaTime));
}
}
The condition may be a check in Y-axis position since your door is going down.