Static Actions

Using static delayed functions in Unity

  • Kendal Cormany
  • December 30,2014

Developing Sketchcross we came across a problem of unrelated objects needed to execute the same functions, statically, with delays.

The solution came almost like an accident. We use LeanTween as our tweening plugin, its open source!, and use it all the time to add flavor and player feedback to our games. While looking up some additional functionality I came across setOnComplete. This required a System.Action, what was that? Was it like a delegate? The short answer is yes, and opened up new possibilities of using this plugin.

Here is what I wanted to do; I wanted any object that contains a spriterenderer to be able to flash a color. So I created a static class that will be used manipulate objects as they are passed in.

First you have to set up your actions that you are going to use


These require a method and must be of c# generic object to work with LeanTween.

Here are the public static methods that we will use when we want to call these functions. I have one called Clicked which will multiply a color for .01 seconds then return, the other Hold that will hold on a color indefinably. In these functions I call upon LeanTween to create a new tween and to set its onComplete function to the actions we defined. Now we don’t actually want the tween to move then object, so I give the tween the end position to be the position that the object was already in. Keep in mind move and movelocal must combine with position or localposition.

Now what will happen when the .01 second delay happens? Here we define these functions that we gave our actions earlier. We pass in a system object then use to cast it back into a GameObject so that we can use it. These methods are simple as all we are doing is changing the spriterenderer’s color.

The class is finished and all we have to do is call Class.Clicked(This.gameobject) and it will happen.

As with any programming there are multiple ways to do any one thing. Something that would also work was to overload the GameObject class then add in these functions. Now like the LeanTween method every Gameobject can execute these methods without instantiating a helper object.

This also is a case for good technical design, if I thought things through better maybe these issues would not arise. But then again a lot of things aren’t problems until they cause a problem.