LeanTween Event Dispatching

LeanTween now supports an easier way to send messages to other parts of your code: Event Dispatching! In Unity it is often necessary to connect far-flung pieces of code together. This can usually be accomplished with some type of GameObject.Find(“objectName”); or setting a reference through the editor. These solutions can sometimes be clunky to say the least, and too much work.

Now there is a better way to send messages to another class, through the LeanTween.dispatchEvent method (to see the code: download the examples from Github). All you need to do is tell LeanTween what methods will be listening like:

void Start(){

LeanTween.addListener(gameObject, (int)MyEvents.CHANGE_COLOR, changeColor);

}

// The event listener

void changeColor( LTEvent e ){ }

Then anywhere in your code (in a different class, and or object) you can send a message to the listener with LeanTween.dispatchEvent:

LeanTween.dispatchEvent( (int)MyEvents.CHANGE_COLOR, transform);

// the second parameter is for passing data

That’s it! No need to keep a lot of references to all the object you will possibly be communicating with.

Below is an example of bunch of avatars that have no references to each other. When you click on one of them they send a message to all the other avatars:

Click an avatar to spread the rainbow!

The example is running in Flash, because LeanTween is still committed to supporting the Flash Export option.

Now dispatching events is more of a convenience thing, it is not recommended in all situations. Although the performance is quite good, in extreme situations you will get better performance by keeping a reference to a Class.

What does this have to do with tweening?

It doesn’t, it’s just a convenient system to have in there. It doesn’t promise to be the be-all end-all of event systems, but for my uses it’s been quite satisfactory.

See it in action:

Download the examples from Github

article thumb:

