Event-based Coroutine

From Unify Community Wiki
Jump to: navigation, search

Author: Kspr

Contents

Description

This is a MonoBehavior that triggers an event, and a script that creates a handler for listening. This is fairly trivial, except it triggers an IEnumerator-function which can be yielded and started as a normal Coroutine. This is useful in many situations, such as displaying a Coroutine-based animation upon doing a MouseClick.

Usage

In this example, InterfaceButton is a MonoBehavior which should be attached to a GameObject with a collider, so it can listen for MouseClicks. Place InterfaceButtonListener on another GameObject.

InterfaceButton

using UnityEngine;
 
using System;
using System.Collections;
 
public class InterfaceButton : MonoBehaviour
{
	public event Func<InterfaceButton, IEnumerator> ButtonPressedCoroutine = null;
 
	IEnumerator OnMouseDown()
	{
		if (ButtonPressedCoroutine != null)
		{
			yield return StartCoroutine(ButtonPressedCoroutine(this));
		}
	}
}

InterfaceButtonListener

using UnityEngine;
 
using System;
using System.Collections;
 
public class InterfaceButtonListener: MonoBehaviour
{
	public InterfaceButton InterfaceButton;
 
	void Start()
	{
		InterfaceButton.ButtonPressedCoroutine += HandleButtonPressedCoroutine;
	}
 
	IEnumerator HandleButtonPressedCoroutine(InterfaceButton ib)
	{
		yield return StartCoroutine(DoSomethingWith(ib));
	}
}

Notes

This may seem trivial, but I have yet to find good examples of this on Google, despite many people asking about it. Unlike some examples of solutions, this one will also work on multiple events connected to the same handler.

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox