Here is a recap. In article 1 we used an RX approach for the following (academic) exercise;
Exercise: Dispatch a double click event based on custom timing parameters.
Reactive Extensions (RX) Solution
You can see the code is easy to read and powerful. While this algorithm requires state management, we don’t have to handle it directly. The internals of RX do it for us. You can imagine with a more complex feature, the code would be dramatically more than the RX solution. Below we break-down the code and explain each step.
NOTE: The TLP Library used in this article is a work in progress. It features only limited functionality and does not conform to common RX standards in the naming, signature, and structure of major elements. These differences are why the syntax and marble diagram names below are not 100% coincidental, but the concepts are similar.The TLP team invites other developers to fork the library and contribute to it. Still it is a fantastic learning tool and quite useful as-is.
Complete Code For RX Solution
[actionscript3 collapse=”true”]
//————————————–
// Methods
//————————————–
///<summary>
/// Use this for initialization
///</summary>
void Start ()
{
// VARIABLES
float maxTimeAllowedBetweenSingleCLicks_float = 1;
float delayBetweenAllowingADoubleClick_float = 5;
int clicksRequiredForADoubleClick_int = 2;
// CREATE OBSERVABLE
//(ORDER IS NOT IMPORTANT, BUT SUBSCRIBE MUST BE LAST)
var mouseDoubleClickObservable = Observable
//RUN IT EVERY FRAME (INTERNALLY THAT MEANS Update()
.everyFrame
//FILTER RESULTS OF THE FRAME
//WE CARE ONLY ‘DID USER CLICK MOUSE BUTTON?’
.filter (
_ =>
Input.GetMouseButtonDown (0)
)
//DID WE FIND X RESULTS WITHIN Y SECONDS?
.withinTimeframe (clicksRequiredForADoubleClick_int, maxTimeAllowedBetweenSingleCLicks_float)
//REQUIRE SOME ‘COOL-DOWN-TIME’ BETWEEN SUCCESSES
.onceEvery (delayBetweenAllowingADoubleClick_float);
//FOR EVERY EVENT THAT MEETS THOSE CRITERIA, CALL A METHOD
var subscription = mouseDoubleClickObservable
.subscribe (
_ =>
_onMouseEvent (MouseEventType.DoubleClick)
Marble diagrams are frequently in videos and blog entries from the Rx team explaining how certain operators in Rx work. From top to bottom there are; source stream(s), operators, and then the outgoing stream. The RXJava wiki has an especially pretty set of these images.
Let’s take a closer look at the syntax we used.
1. everyFrame: We observe an event stream on every frame (aka Update) in Unity…
2. filter: …where the mouse button is down…
3. withinTimeFrame: … X occurrences within Y seconds, which we call success…
4. onceEvery: …and success can only happen every Z seconds…
5. subscribe: …then call the desired method…
1. Operator: everyFrame (Similar to fromEvent)
From RXJava, we see that “the free-threaded nature of Rx is key to the performance characteristics of the event processing pipeline. However, in places where we bridge with the external world, this sometimes has negative effects due to thread-affine operations involved. The FromEvent [Pattern] bridges are one such place where we reach out to add and remove operations on events”.
Our specific use of everyFrame(), in pseudocode, would be like fromEvent (myMonoBehavior.Update).
2. Operator: filter
You can filter an Observable, discarding any items that do not meet some test, by passing a filtering function into the filter( ) method. For example, the following code filters a list of integers, emitting only those that are even (that is, where the remainder from dividing the number by two is zero):
3. Operator: withinTimeFrame (Similar to buffer)
The buffer( ) method periodically gathers items emitted by a source Observable into bundles, and emits these bundles as its own emissions. There are a number of ways with which you can regulate how buffer( ) gathers items from the source Observable into bundles:
4. Operator: onceEvery (Similar to sample)
5. Operator: subscribe
Subscribe is not an operator per se, it is something higher level in importance — When an observer subscribes to an observable sequence, the sequence begins and runs till completion. It is in the subscribe that we answer “What should ultimately happen with the outgoing event stream?”. In our example, we call a local method _onMouseEvent and we pass an appropriate MouseEventType.
NEXT STEPS
Our exploration into RX has just begun. Everyone interested is invited to download the source-code from my first article “Unity3D Reactive Extensions 1: An Introduction” and learn more. I continue to seek to find the best RX library for Unity development and have already begun to add RX into my game projects.`
Obviously fantastic software can be created without RX. We work without it every day. So why consider it? Well, essentially because asynchonous programming is hard to do, brittle, and is a challenge to scale. Well as the Reactive Manifesto explains;
The Need To Go Reactive – Each day applications are getting bigger, users expect more to happen in less time, and our projects are deployed to increasingly diverse set of (smaller) devices. To compete, old dogs need new tricks.
Reactive Applications – They react to events; loading data, user gestures, system failures.
Event-Driven – Event driven systems feature loose coupling between components and subsystems; a prerequisite for scalability and resilience.
Scalable – With RX our data runs ‘as if’ it is synchronous. Even the currently synchronous stuff. So as complexity comes and delays ensue, it can flex to be asynchronous. Secondly, the decoupled nature allows for location transparency. Benefits include multi-threading (where possible).
Resilient – In a reactive application, resilience is not an afterthought but part of the design from the beginning (see ‘onError’). Making failure a first class construct in the programming model provides the means to react to and manage it, which leads to applications that are highly tolerant to failure by being able to heal and repair themselves at run-time.
Responsive – The philosophies and practices of RX programming seek minimal latency to the user experience.
Conclusion – We expect that a rapidly increasing number of systems will follow this blueprint in the years ahead.
NOTE: While RX is designed to work with asynchronous data streams, it really doesn’t care. RX blindly accepts synchronous data within the same data flow.
Games
My first exposure to RX was regarding both UI behaviors (e.g. mouse events) and asynchronous data (e.g. loading from server). Gaming is inherently an asynchronous experience and the UI behaviors (e.g. user input) alone warrant a deep look at RX.
What is RX?
Iterables You are probably familiar with the concept of Iterables. In Unity we are used to using a List of values and looping through them and doing something synchronously. Observables In RX, it is observables that are a similar concept except the list may or may not be populated yet (i.e. it could start out empty) and may or may not be fully populated yet (i.e. ‘complete’). Still you iterate through the values, however asynchronously. Consider the following table;
Same Concept, Opposite Direction (Pull vs Push of Data)
Iterable (Pull)
Observable (Push)
getDataFromLocalMemory()
.skip(10)
.take(5)
.map({ s -> return s + " changed" })
.forEach({ println "next => " + it })
getDataFromNetwork()
.skip(10)
.take(5)
.map({ s -> return s + " changed" })
.subscribe({ println "onNext => " + it })
Reactive applications use observable models, event streams and stateful clients.
Reactive extensions (RX) is the library designed for Functional Reactive Programming (FRP). It is “a library for composing asynchronous and event-based programs by using observable sequences.” What is FRP? The name comes from the language features used and the philosophy of the data exchange (See Figure 1).
According to Haskell.org, Functional Reactive Programming (FRP) integrates time flow and compositional events into functional programming. This provides an elegant way to express computation in domains such as interactive animations, robotics, computer vision, user interfaces, and simulation. The major parts of RX;
Observables – Source of event stream & Subscriber – Observer of event stream.
Linq – Query the event stream (e.g. filter, map, zip)
Schedulers – Define the timing (inc. frequency) of concurrency.
As a quick primer, consider the following Observer->Subscriber event stream (See Figure 2).
Here the Observable emits an integer, it goes through an operation that adds 2 to it, and is finally received by the Subscriber (Observer). All steps are asynchronous, which means the subscriber does not actually know that the original value had been changed.
Operators
Between the Observable and the Subscriber the event stream can be operated upon. Here is a partial list of operators;
Transforming
map( ) — transform the items emitted by an Observable by applying a function to each of them
scan( ) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value
Filtering
filter( ) — filter items emitted by an Observable
takeLast( ) — only emit the last n items emitted by an Observable
skip( ) — ignore the first n items emitted by an Observable
takeFirst( ) — emit only the first item emitted by an Observable, or the first item that meets some condition
Combining
startWith( ) — emit a specified sequence of items before beginning to emit the items from the Observable
merge( ) — combine multiple Observables into one
zip( ) — combine sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function
How to do RX?
Let’s consider a very typical operation; using mouse input to perform a simple operation. Compare the non-RX and RX approaches to the following (academic) exercise;
Exercise: Dispatch a double click event based on custom timing parameters.
Reactive Extensions (RX) Solution
You can see the code is easy to read and powerful. While this algorithm requires state management, we don’t have to handle it directly. The internals of RX do it for us. You can imagine with a more complex feature, the code would be dramatically more than the RX solution. You can read an in depth analysis of this code in my next article “Unity3D Reactive Extensions 2“.
[actionscript3 collapse=”true”]
//————————————–
// Methods
//————————————–
///<summary>
/// Use this for initialization
///</summary>
void Start ()
{
// VARIABLES
float maxTimeAllowedBetweenSingleCLicks_float = 1;
float delayBetweenAllowingADoubleClick_float = 5;
int clicksRequiredForADoubleClick_int = 2;
// CREATE OBSERVABLE
//(ORDER IS NOT IMPORTANT, BUT SUBSCRIBE MUST BE LAST)
var mouseDoubleClickObservable = Observable
//RUN IT EVERY FRAME (INTERNALLY THAT MEANS Update()
.everyFrame
//FILTER RESULTS OF THE FRAME
//WE CARE ONLY ‘DID USER CLICK MOUSE BUTTON?’
.filter (
_ =>
Input.GetMouseButtonDown (0)
)
//DID WE FIND X RESULTS WITHIN Y SECONDS?
.withinTimeframe (clicksRequiredForADoubleClick_int, maxTimeAllowedBetweenSingleCLicks_float)
//REQUIRE SOME ‘COOL-DOWN-TIME’ BETWEEN SUCCESSES
.onceEvery (delayBetweenAllowingADoubleClick_float);
//FOR EVERY EVENT THAT MEETS THOSE CRITERIA, CALL A METHOD
var subscription = mouseDoubleClickObservable
.subscribe (
_ =>
_onMouseEvent (MouseEventType.DoubleClick)
This code requires us to ‘manually’ maintain state. You can imagine with a more complex feature, the code here would be even more long-winded compared to the RX equivalent. Thankfully we can use Coroutines, otherwise there would be even more state-specific variable setup to write and maintain.
[actionscript3 collapse=”true”]
/// <summary>
/// KEEPING STATE: Timing information
/// </summary>
private int _state_clicksInLastXSeconds_int = 0;
NOTE: The Unity source-code for this article is available (See ‘Member Resources’ below).
RX & Unity
RX is a library that can be theoretically ported to any language. It currently exists in many languages; prominently Java and JavaScript. There are C# ports, but unfortunately not all are Unity-compatible. Unity’s (latest version 4.3.4) C# is compatible with an OLD version of Mono – Mono v2.65 (versus the latest available v3.2.7). Mono is the open source version of .NET which powers the C# language features of Unity. So, while RX libraries in C# are plentiful, there is not yet a Unity-compatible library which contains all the features we would like to see. All examples covered int his article are from the amazing people at Tiny Lab Production (TLP). Their RX library is available for free download (See ‘Member Resources’ below). The TLP team actively encourage use of and contribution to their library
RX Integration
Uses of RX
My first experimentation includes creating mostly non-RX games with few distinct RX elements (particularly mouse/key/gesture input scenarios). RX can be peppered into your project selectively. With more experience and awareness I expect the community to embrace more systemic usage of RX in Unity games. Ideas for RX In Gaming;
User Input (Mouse/Keyboard/Touch)
Constraints (keep player character onscreen)
Loading Assets
Loading From Backend Services
Multiplayer game state synchronization (e.g. ‘Did every player in this game room click start?’)
The RX library you choose must match your platform of choice. For me that is Unity & C#. Due to the “RX & Unity” issues above I can’t simply choose any C# library. The library chosen for this article was created by the fine developers at Tiny Lab Productions (TLP). I continue to search for a Unity-friendly library that has the scope and syntax exactly matching Netflix’s fantastic RxJava implementation.
NOTE: The TLP Library used in this article is a work in progress. It features only limited functionality and does not conform to common RX standards in the naming, signature, and structure of major elements. The TLP team invites other developers to fork the library and contribute to it. Still it is a fantastic learning tool and quite useful as-is.
Resources
While RX is new to the Unity Community, there are tons of non-Unity resources and tutorials available. Its important to note that until a robust Unity-compatible RX library is available all of the functionality may not be available. Here are some resources;
RxJava Documentation (A Must Read First) Functional Reactive Programming on the JVM (by the Netflix team)
The RX example above uses combinators to empower the event stream filtration and modification. Deeper explanation is available in my next article “Unity3D Reactive Extensions 2“.
Member Resources
[private_Free member]Enjoy this members-only content!
Unity3D is a powerful suite of tools (Project IDE, Code IDE, run-time) for game development. A fantastic way to accelerate Unity & C# learning, empower development, and even make some money using the Unity Asset Store.
In my previous article “Introduction To the Asset Store” we see a complete Intro to the Unity Asset Store including how you can Fund your Indie Game Development by creating assets. Now let’s hear from some key developers who have published successful content.
With 4 years experience in Unity, the team at Lumo Dev first created game examples in c#. Due to demand the product is also available in Java. Lumo found that new developers may not be sure where to start when planning a complete game, so their game templates help accelerate the learning process. The team confides that they too learn greatly from others’ work too.
Throw your product out there! Don’t wait until you created the best product before getting it out. Later, you can always go back and redo stuff, but the important thing is to get experience. – Lumo Dev Team
Jasper Stocker’s most popular product is Camera Path, but since its success he shifted focus. He now specializes in creating procedurally generated content. He has 5-6 years of experience so far with Unity.
I offer tools in a single (programming) language so I didn’t have to maintain two codebases. C# is dominant. I use every time. It’s a bit of a no brainer.
Q: Advice for Unity Game Developers? A: Learn to extend the editor. It’s pretty simple and you can make some really powerful tools. You can get rid of a lot of boring work by automating it. You can also make things designers might use the make levels more dynamic.
Q: Tips for Asset Store Devs? A: Work hard to make something robust and test the hell out of it. Try to break it by acting like a bored 5 year old.
Fabio has 3 years experience with Unity. He creates collections of materials/textures/shaders. He estimates he has spent 100-150 hours learning Unity, doing R&D for his assets, and creating them.
Mixed Dimensions has 5+ years experience with Unity development for many platforms (Web/IOS/Android/Windows/Mac). Lead, Muhannad confirms that his popular plugins have been downloaded thousands of times and his team continues to update the leading products every month. His tools depend on (and include) existing libraries such as LZMA, ClipperLib, and Poly2Tri (all Managed .NET).
Focus on mobile games and create something that has a need. – Muhannad from Mixed Dimensions.
Many Thanks
I am grateful to these developers for sharing some of their experiences.
Unity3D is a powerful suite of tools (Project IDE, Code IDE, run-time) for game development.
A fantastic way to accelerate Unity & C# learning, empower development, and even make some money using the Unity Asset Store.
Asset Store
The Unity IDE offers an Asset Store. If you haven’t yet familiarized yourself with the Asset Store, this is the best time to dive in. You’ll find nearly everything a game developer could wish for– complete template projects, models of every shape and size, countless textures and materials, an extensive set of code libraries, hours of professional music and sound effects, and a broad selection of editor extensions to bring new functionality to Unity. Best of all, we’ve gone out of our way to make sure that these offerings are both affordable and covered by a common, easy-to-use license without legal complexities such as royalties.
I think of the store like a (sometimes free) bag of temporary art while I work. More rarely, when tackling a technical challenge I check the store to see if another developer has solved my needs and created a code library. The naming for an asset store ‘item’ doesn’t seem standardized, but when I say 3rd party code-library, package, or plugin I mean the same thing. I mean a collection of code or visual/audio art which augment the IDE itself and/or enable richer development.
Something remarkable, and quite different than the Flash community, is that these packages can actually add functionality to the Unity3D IDE itself. New first-class menus, panels, UI Gizmos, etc… It is truly amazing.
Unity Technologies, the creators of Unity3D share the revenue from every paid purchase made. My opinion is that this revenue stream for the company helps them support the free version of Unity. More developers using Unity creates a larger pool of asset store contributors and purchasers.
Finding Asset Store Content
From within the Unity IDE (Menu -> Window -> Asset Store) or through your web browser online you can shop in the store. Search by product name or developer name, see featured items, or simply browse based on popular categories.
Categories Include;
3D Models
Animation
Audio
Complete Projects
Editor Extensions (My Favorite!)
Scripting
Textures
& Much more…
To research this article, I scoured the community thoroughly, interviewed top developers on their favorites, and tested out many plugins to build the definitive list of the best asset store content for developers. Here is are the Essential Unity3D Plugins / Packages. All are compatible with both free and pro versions of Unity.
But who is it that is making this great content? Well, there are many prolific contributors.
Asset Store Contributors
As successful developer Daniel Sklar of ProfiDevelopers explains, the Asset Store is successfully being used all over the world. After many years in game development, his team has gained a lot of experience which they pass on in the form of well designed assets. Greener teams can save time and money by using existing content.
More recently, Unity Technologies has partnered with asset store contributors to market some key packages. These projects may be developed outside of the core company but get favorable promotion, marketing, and exposure.
Popular Unity Partnership Packages
Everyplay! is a newer addition to the store. This innovative service is a complete solution for monetizing, acquiring and engaging users. Everyplay enables users to share their best gaming moments directly from within the game as video!
With Kii, game developers get a fast and scalable back-end, powerful analytics and game distribution services, so they can focus on the stuff that matters — the game experience.
GameAnalytics automatically takes care of all the basic tracking/analytics needs for your game. All you have to do is interpret the results.
PaeDae is how you monetize your game with in-game advertising without breaking its cohesive gameplay experience.
Unity 1st Party Packages
As developers we typically see new features added to the Unity tool itself. You download the latest version of the IDE and checkout the release notes to see what new features are available. However, a second way for Unity Technologies to distribute non-essential functionality is through the asset store. These 1st Party Packages include complete game projects, assets for learning how to use Unity, as well as for testing your existing projects.
An inspiring article on the Unity Blog explains how we can all Pay for our Indie games via Asset Store work. Although it isn’t easy, making a living through the Asset Store has been possible for at least two years. It all depends on your expenses, the appeal and pricing of your product, the competition, your skills and what you are willing to sacrifice (more on that later).
Using Asset Store To Fund Your Indie Game
Stay alive by some means during the early days. Game design consulting was ideal for me. I could do it one day per week.
Design your game early on to know its technical needs and requirements (later you will want to identify all kinds of synergies in order to minimize cost).
Build some game generic features or content that will be part of your game. Make these modular and possible to “productify”.
Sell your content in the Asset Store and use the earnings to fund your game.
This approach has many benefits:
Starting making revenue DURING the production of your game.
Learning opportunities: Support, business and economics, marketing strategies, teamwork, collaboration, etc…
Network with other Asset Store developers
Encourage modularity in your codebase
You may FIND existing Asset Store packages that save you time.
Promoting Asset Store Packages
Maybe you’ve created a great 3D model or an editor extension for Unity, but now it’s sitting at the Asset Store shelves and gathering dust. What can you do to sell more and fund your game and your life with your awesome asset? A few really successful publishers have shared their promotion tips and we cooked them up into this advice.
In my 13+ years as a pro game developer, community involvement has always been important. Involvement in groups, conferences, and open source projects helps me stay connected, teach, and learn new things. Its for these reasons, more than just profit that I’m interested in the Unity Asset Store.
Here are the in-progress diaries of a few packages.
uMOM – Unity Manager of Managers, game framework (link)
I encourage everyone to get involved as a consumer and potential contributor to the asset store. It is an incredibly powerful way to take advantage of the powerful community around Unity.
After years of consulting success, I am shifting goals for the next phase of my career.
I am now actively seeking a full-time position as a Unity3D Game Developer.
I have deep experience in game development; more than 13 years of professional work. I absolutely live and breath gaming. I love it. I have much to offer my next team — everything from game concept creation and development, through to launch — and I am very excited! Here you can learn about my skills and experience ( RivelloMultimediaConsulting.com/forecast/ ) and contact me ( RivelloMultimediaConsulting.com/contact/ ) to setup a time to talk — before, during, or after GDC.
1. GDC Goals
Geek Out! – As a lifetime video game fantastic, I am incredibly psyched to see some great sessions about my favorite games of 2013/2014.
Connect to the community — While American, I have worked internationally for many years.
Plug-in to the presenter-scene — I’d like to get a feel for who is talking, how, and about what subjects. My focus is mobile. And the mobile space, while growing, it is still marginalized at GDC. As an experience public speaker (360|Flex, Adobe Max, Adobe Camp Brazil, FlashForward, FITC, LA Games Summit, Montreal Game Summit, RIA Adventure Cruise, Rich Media Institute, … ) I would like to speak at GDC 2015 and Unite 2015 next year. There are some session I will attend — more to experience the speaker himself/herself than to see the content.
2. GDC Social Schedule
I’m excited to meet new contacts and reconnect with old friends during GDC. Outside of the conference sessions, I’m excite to block out time for more fun.
Are you hiring? Want to to talk about great video games? Or just explore amazing San Francisco?
Update: The event has ended. Thanks to all the great people I met.
Suggested Meeting Places GDC is huge and it can be hectic to meet on site. Here are a few nearby locations within walking distance of the event’s Mosocone Center. Note that 20,000 people attend GDC and everyone needs to eat. Long delays! Also, some of these businesses have multiple locations, so the address is included.
Coffee/Drink (Walking Distance)
The W Hotel (181 3rd St.) lounge is a happening spot with trendy cocktails and a good wine list.
The Thirsty Bear (661 Howard St.) is a comfy, bustling brewery that serves authentic Spanish tapas.
Jillian’s (175 Fourth St.) is an upscale sports bar with large-screen TVs and billiard tables.
The SF MOMA Cafe (1082 Folsom St.) offers tasty biscotti and outdoor seating
Blue Bottle Coffee (66 Mint Plaza) is a cult favorite among locals who appreciate individually brewed cups of java;
Peet’s (4th and Harrison) is the place to grab a quality cup to go.