<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gbros Games Studio on Medium]]></title>
        <description><![CDATA[Stories by Gbros Games Studio on Medium]]></description>
        <link>https://medium.com/@gbrosgames?source=rss-7f35175f9e43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rBFSEBW8YehXuwQ9i-BHpA.png</url>
            <title>Stories by Gbros Games Studio on Medium</title>
            <link>https://medium.com/@gbrosgames?source=rss-7f35175f9e43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:16:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gbrosgames/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Leveraging SerializeReference for Flexible Commands in Unity Game Development]]></title>
            <link>https://medium.com/@gbrosgames/leveraging-serializereference-for-flexible-commands-in-unity-game-development-614e336b03b9?source=rss-7f35175f9e43------2</link>
            <guid isPermaLink="false">https://medium.com/p/614e336b03b9</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Gbros Games Studio]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 13:59:50 GMT</pubDate>
            <atom:updated>2023-08-13T08:33:45.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Power of SerializeReference, Command Patterns, and Conditions</h4><h4>Introduction</h4><p>In the fast-paced world of game development, time is often a precious commodity. Finding efficient solutions that offer quick testing and flexible configuration becomes paramount. We, too, faced this challenge and discovered a potent approach that not only met these demands but also allowed us to customize our domain’s behavior extensively.</p><p>Our secret weapon? The [<a href="https://docs.unity3d.com/ScriptReference/SerializeReference.html">SerializeReference</a>] attribute coupled with a tailored Condition/Command pattern. While our exploration of this technique is still ongoing, the preliminary results are incredibly promising. We’re excited to share our insights and invite you to join the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5o1yx3rx6jBHbk92ZINOA.jpeg" /></figure><p>If you’re curious about the base capabilities of SerializeReference, check out this basic yet powerful example in <a href="https://www.reddit.com/r/Unity3D/comments/14y0c1q/serializereference_is_very_powerfull_why_is_no/">Reddit thread</a>.</p><p>Let’s dive into the tools that helped us craft this solution:</p><ul><li><strong>UniTask</strong>: A free library offering efficient allocation-free async/await integration for Unity.</li><li><strong>OdinInspector</strong>: A library that facilitates instance creation from dropdowns using the [SerializeReference] attribute (You can also create custom editors or explore alternatives like <a href="https://github.com/mackysoft/Unity-SerializeReferenceExtensions">Unity-SerializeReferenceExtensions</a>. These tools emphasize the use of Commands through <strong>SerializeReference</strong>, with a special nod to the added brilliance when employing async/await principles.</li></ul><h3>Unleashing Commands:</h3><p>But what exactly are these “commands” we keep referring to? In essence, commands are serializable configurations of actions that can be executed within a given context. They’re like the building blocks of dynamic behavior in your game.</p><pre>public interface ICommand&lt;TContext&gt;<br>{<br>    UniTask ExecuteAsync(TContext context, CancellationToken cancellationToken);<br>}</pre><p>Let’s explore some examples:</p><h4>Simple Contextual Commands for Character Behavior:</h4><pre>public class RestoreHPCharacterCommand : ICharacterCommand<br>{<br>    public UniTask Execute(Character context, CancellationToken cancellationToken)<br>    {<br>        context.RestoreHP();<br>        return UniTask.CompletedTask;<br>    }<br>}</pre><pre>public class ModifyStatisticCharacterCommand : ICharacterCommand<br>{<br>    public Id StatisticId;<br>    public float Value;<br><br>    public UniTask Execute(Character context, CancellationToken cancellationToken)<br>    {<br>        context.GetStatistic(StatisticId).ModifyBy(Value);<br>        return UniTask.CompletedTask;<br>    }<br>}</pre><h4>Versatile Commands for Any GameObject:</h4><p>Behold an asynchronous command example:</p><pre>public class MoveGameObjectCommand : IGameObjectCommand<br>{<br>    public Vector3 Direction;<br>    public float Duration;<br>    public float Distance;<br>    public async UniTask Execute(GameObject context, CancellationToken cancellationToken)<br>    {<br>        var startTime = Time.time;<br>        var initialPosition = context.transform.position;<br>        var targetPosition = initialPosition + Direction.normalized * Distance;<br>        while (Time.time - startTime &lt; Duration)<br>        {<br>            float progress = (Time.time - startTime) / Duration;<br>            context.transform.position = Vector3.Lerp(initialPosition, targetPosition, progress);<br>            await UniTask.Yield(PlayerLoopTiming.Update, cancellationToken: cancellationToken);<br>        }<br>        context.transform.position = targetPosition;<br>    }<br>}</pre><h4>Building Blocks with Boilerplate Commands:</h4><p>Meet the Command Group — a highly useful construct enabling the execution of multiple commands in parallel or sequentially:</p><pre>public class CommandGroup&lt;TCommand, TContext&gt; : ICommand&lt;TContext&gt; where TCommand : ICommand&lt;TContext&gt;<br>{<br>    public List&lt;TCommand&gt; Commands = new();<br>    public bool ExecuteInParallel = true;<br><br>    public async UniTask ExecuteAsync(TContext context, CancellationToken cancellationToken)<br>    {<br>        if (ExecuteInParallel)<br>        {<br>            await UniTask.WhenAll(Commands.Select(item =&gt; item.ExecuteAsync(context, cancellationToken)));<br>            return;<br>        }<br><br>        foreach (var item in Commands)<br>        {<br>            await item.ExecuteAsync(context, cancellationToken);<br>        }<br>    }<br>}</pre><p>Enter the Delay Command — perfect for orchestrating pauses between command executions:</p><pre>public class DelayCommand&lt;TContext&gt; : ICommand&lt;TContext&gt;<br>{<br>    public float DelayMs;<br>    public UniTask ExecuteAsync(TContext context, CancellationToken cancellationToken)<br>    {<br>        return UniTask.Delay(TimeSpan.FromMilliseconds(DelayMs), cancellationToken: cancellationToken);<br>    }<br>}</pre><p>Bridge the Unity world with the UnityEventCommand, facilitating actions like starting particle systems or toggling game objects:</p><pre>public class UnityEventCommand&lt;TCommand, TContext&gt; : ICommand&lt;TContext&gt; where TCommand : ICommand&lt;TContext&gt;<br>{<br>    public UnityEvent Event;<br>    public UniTask ExecuteAsync(TContext context, CancellationToken cancellationToken)<br>    {<br>        Event?.Invoke();<br>        return UniTask.CompletedTask;<br>    }<br>}</pre><h4>Conditions: Expanding Behavior Horizons</h4><p>Conditions are an integral piece of the puzzle, perfectly complementing the concept of commands. With conditions, we can create complex behaviors by weaving together simple atomic actions. This enables us to craft dynamic and nuanced gameplay experiences, allowing our games to react intelligently to a variety of scenarios.</p><h4>What Are Conditions in the Context of Commands?</h4><p>Conditions are logic checks that determine whether a certain command or set of commands should be executed based on the state of the game. This powerful addition allows us to create decision branches that respond dynamically to the gameplay context.</p><pre>public interface ICondition&lt;TContext&gt;<br>{<br>    UniTask&lt;bool&gt; ExecuteAsync(TContext context, CancellationToken cancellationToken);<br>}</pre><h4>Examples of Condition-Driven Behavior:</h4><ul><li>If a character’s HP drops to 0, execute the PlayFeedbacksCommand</li><li>Depending on the damage severity from a DamageInfo context, trigger either a Critical Effect or a Default Effect</li><li>If the DamageType is Fire, apply fire-related effects</li><li>If the MagicShield’s energy level is above 50%, enable the HighEnergy Effect and disable the LowEnergy Effect</li></ul><h4>Creating Condition Groups: All or Any</h4><p>To harness the full potential of conditions, we can group them together to create more intricate decision-making structures. These groups allow us to determine whether all conditions must be met before executing a command or if just a single condition suffices.</p><pre>public class ConditionGroup&lt;TCondition, TContext&gt; : ICondition&lt;TContext&gt; where TCondition : ICondition&lt;TContext&gt;<br>{<br>    public enum GroupType<br>    {<br>        All,<br>        Any<br>    }<br><br>    [EnumToggleButtons] public GroupType Type;<br>    [SerializeReference] public List&lt;TCondition&gt; Conditions = new();<br><br>    public async UniTask&lt;bool&gt; ExecuteAsync(TContext context, CancellationToken cancellationToken)<br>    {<br>        if (Type == GroupType.All)<br>        {<br>            foreach (var condition in Conditions)<br>            {<br>                if (!await condition.ExecuteAsync(context, cancellationToken))<br>                    return false;<br>            }<br>            return true;<br>        }<br>        else if (Type == GroupType.Any)<br>        {<br>            foreach (var condition in Conditions)<br>            {<br>                if (await condition.ExecuteAsync(context, cancellationToken))<br>                    return true;<br>            }<br>            return false;<br>        }<br>        return false;<br>    }<br>}</pre><h4>Condition-Driven Command Execution</h4><p>The synergy between conditions and commands allows us to craft more sophisticated behaviors. The `ConditionCommand` enables us to execute specific commands based on whether a condition is met or not. This adds a layer of intelligence to our gameplay, making it react dynamically to the context.</p><pre>public class ConditionCommand&lt;TCondition, TCommand, TContext&gt; : ICommand&lt;TContext&gt;<br>    where TCommand : ICommand&lt;TContext&gt;<br>    where TCondition : ICondition&lt;TContext&gt;<br>{<br>    [SerializeReference] public TCondition Condition;<br>    [SerializeReference] public TCommand Command;<br>    [SerializeReference] public TCommand ElseCommand;<br>    public async UniTask ExecuteAsync(TContext context, CancellationToken cancellationToken)<br>    {<br>        var result = await Condition.ExecuteAsync(context, cancellationToken);<br>        if (result)<br>        {<br>            if (Command == null) return;<br>            await Command.ExecuteAsync(context, cancellationToken);<br>        }<br>        else<br>        {<br>            if (ElseCommand == null) return;<br>            await ElseCommand.ExecuteAsync(context, cancellationToken);<br>        }<br>    }<br>}</pre><h4>Pros and Cons:</h4><p>Pros:</p><ul><li>Modularity</li><li>Reusability</li><li>Easy configuration of new behaviors</li><li>Exceptionally flexible solution accommodating various scenarios</li><li>Leveraging presets for streamlined development</li></ul><p>Cons:</p><ul><li>Potential complexity in inspector-side configuration</li><li>Involvement of boilerplate code</li><li>Dependency injection challenges</li></ul><h4>Summary</h4><p>In the dynamic realm of Unity game development, integrating <strong>SerializeReference</strong>, the Command pattern, and Conditions isn’t just a fancy idea; it’s a game-changer. This trifecta offers tangible benefits that can transform your game development process:</p><ul><li>Flexibility Unleashed: Embrace the power to mold behaviors on the fly. Whether it’s character actions, environmental responses, or narrative twists, this approach adapts to your creative whims.</li><li>Efficiency Amplified: Streamline your workflow with a unified toolkit. No need to reinvent the wheel for every system; these tools seamlessly integrate across components and ScriptableObjects.</li><li>Engagement Elevated: Craft gameplay that reacts to players choices and actions. From immersive weather shifts to intricate dialogue trees, this approach enhances player immersion and investment.</li><li>Reusability Simplified: Create components and behaviors that can be easily reused across your project. Save time and effort while maintaining consistent and polished gameplay elements.</li><li>Innovation Unlocked: Experiment with combinations and possibilities that breathe life into your game. The synergy between these techniques sparks innovation and elevates your game above the ordinary.</li></ul><p>So, as you embark on your next Unity adventure, remember that the fusion of <strong>SerializeReference</strong>, the Command pattern, and Conditions isn’t just a theory — it’s a practical gateway to a richer, more responsive, and thoroughly enjoyable game development journey. Start integrating these tools, watch your game thrive, and relish in the joy of creating something truly exceptional. Your game awaits its transformation!</p><h4>Resources</h4><ul><li><a href="https://github.com/neuecc/UniRx">UniRx Library</a></li><li><a href="https://assetstore.unity.com/packages/tools/utilities/odin-inspector-and-serializer-89041">Odin Inspector</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=614e336b03b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Watchers]]></title>
            <link>https://medium.com/@gbrosgames/watchers-549b6cb73eea?source=rss-7f35175f9e43------2</link>
            <guid isPermaLink="false">https://medium.com/p/549b6cb73eea</guid>
            <category><![CDATA[begginer]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[intermediate]]></category>
            <category><![CDATA[unirx]]></category>
            <category><![CDATA[advanced]]></category>
            <dc:creator><![CDATA[Gbros Games Studio]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 14:32:03 GMT</pubDate>
            <atom:updated>2022-06-13T14:32:03.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEv56oWqjrm89yIyzJkYEg.png" /></figure><h3>Introduction</h3><p>Have you ever struggled with jumping from tab to tab, from window to window? Are you tired of the endless journey through the object hierarchy to find the right one? Are you tired of scrolling through countless logs to keep track of <em>that one specific</em> value?</p><p>If you answered yes to any of the above questions, You’ve come to the right place! Jokes aside, in this post we would like to introduce our custom tool called Watchers.</p><p>Watchers is a collection of handy windows and extensions that will speed up your workflow and make your life easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*E0cq1QGy8PTdnKytOws6eg.png" /></figure><h3>Why Watchers</h3><ul><li>most frequently used objects in one place and always at hand</li><li>tracking values of not only UnityEngine.Objects, but also instance values of ordinary classes</li><li>easiness of use</li><li>high extensibility</li><li>native solution</li><li>customizable solution with support for your own styles</li></ul><h3>Unity Installation</h3><p>Since unity doesn’t support git dependencies in package.json you have to install <a href="https://github.com/neuecc/UniRx#upm-package">UniRx</a> manually. Edit manifest.json file in your Unity Packages directory</p><pre>{<br>	&quot;dependencies&quot;: {<br>		&quot;com.gbros.tools.unirx.powerobservables&quot;: &quot;[&lt;https://github.com/GbrosGames/Tools.git?path=Assets/Watchers&gt;](&lt;https://github.com/GbrosGames/Tools.git?path=Assets/Watchers&gt;)&quot;,<br>		&quot;com.neuecc.unirx&quot;: &quot;[&lt;https://github.com/neuecc/UniRx.git?path=Assets/Plugins/UniRx/Scripts&gt;](&lt;https://github.com/neuecc/UniRx.git?path=Assets/Plugins/UniRx/Scripts&gt;)&quot;<br>	}<br>}</pre><h3>General</h3><p>Watchers are created from bunch of UnityEngine.UIElements and UnityEditor.UIElements. Please see blow for detailed introduction to all core classes, methods and use case examples.</p><h3>Watchers</h3><p>Watcher is a base class that holds references to the boards. It’s responsible for clearing all subscriptions on the board. Every watcher can contain multiple boards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*MtNXVmuBCRPHjHvM2wdATg.png" /></figure><h3>Boards</h3><p>Board inherits from Unity native GraphView. It is a place where you can add your Nodes. Boards can contain multiple cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YVilGBZmRXu1tQXItws8iA.png" /></figure><h3>Card</h3><p>Card inherits from Unity native Node. It is the element that can be part of our Graph. You can create and add your custom nodes. Cards are used as data containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nW8FXpLSBWkmoExOKUzivA.png" /></figure><h3>Container</h3><p>Container is styled UIElement with label that can have many UI Elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Ym1QbuPHyMBXokWcyI3ojg.png" /></figure><p>It can be easily extended with your own UIElements and stylized through the Watchers API or with custom .uss files.</p><h3>Getting Started</h3><p>Since watchers is editor only solution to help you with debugging and increase your development speed we have to add proper usings at the top of the class.</p><pre><strong><em>#if UNITY_EDITOR<br></em></strong><strong>using</strong> Gbros.Watchers;<br>#endif</pre><h3>Creating Watcher</h3><h4>Fluent way</h4><pre>[Serializable] <br><strong>public</strong> <strong>class</strong> <strong>SomeClass</strong> <br>{ <br>	<strong>public</strong> Color SomeColor;<br>	<strong>public</strong> <strong>string</strong> SomeText;<br>}<br><br><strong>public</strong> <strong>class</strong> <strong>SomeNotUnityObjectClass</strong><br>{<br>    <strong>public</strong> <strong>int</strong> SomeValue { <strong>get</strong>; <strong>set</strong>; }<br>}<br><br><br><strong>public</strong> <strong>class</strong> <strong>SomeComponent</strong> : MonoBehaviour <br>{<br><br><strong>public</strong> <strong>int</strong> SomeValue = 2;<br><strong>public</strong> Vector2 SomeVector2 = Vector2.up;<br><strong>public</strong> Vector3 SomeVector3 = Vector3.up;<br><strong>public</strong> SomeClass SomeClass;<br><br><strong>private</strong> <strong>void</strong> <strong>Awake</strong>()<br>{<br>    <strong>var</strong> someNotUnityObjectClass = <strong>new</strong> SomeNotUnityObjectClass<br>    {<br>        SomeValue = 123<br>    };<br>		<br>	#<strong>if</strong> UNITY_EDITOR<br>       Watchers.<strong>Watcher</strong>(&quot;Watcher A&quot;)<br>               .<strong>Board</strong>(&quot;Board A&quot;)<br>               .<strong>Card</strong>(&quot;Card A&quot;)<br>               .<strong>Container</strong>(&quot;Container A&quot;)<br>               .<strong>AddSelectorButton</strong>($&quot;Select {gameObject.name}&quot;, gameObject)<br>               .<strong>AddSerializedProperty</strong>(<strong>this</strong>, x =&gt; x.SomeValue)<br>               .<strong>AddSerializedProperty</strong>(<strong>this</strong>, &quot;SomeVector2&quot;)<br>               .<strong>AddSerializedProperty</strong>(<strong>this</strong>, x =&gt; x.SomeVector3)<br>               .<strong>AddSerializedProperty</strong>(<strong>this</strong>, x =&gt; x.SomeClass)<br>               .<strong>AddProperty</strong>(&quot;SomeValue in someNonSerializableClass&quot;, someNotUnityObjectClass, x =&gt; x.SomeValue, x =&gt; someNotUnityObjectClass.SomeValue = x)<br>               .<strong>AddActionButton</strong>(&quot;Some Action&quot;, () =&gt; { Debug.<strong>Log</strong>($&quot;Value from nonUnityObjectClass - {someNotUnityObjectClass.SomeValue}&quot;); });<br>	#endif<br>}</pre><h4>Classic</h4><pre><strong>var</strong> watcher = Watchers.<strong>Watcher</strong>(&quot;Watcher A&quot;);<br>	<strong>var</strong> board = watcher.<strong>Board</strong>(&quot;Board A&quot;);<br>	<strong>var</strong> card = board.<strong>Card</strong>(&quot;Card A&quot;);<br>	<strong>var</strong> cardContainer = card.<strong>Container</strong>(&quot;Container A&quot;);<br>	<em>// add whatever VisualElement to your cardContainer</em></pre><h4>Nested</h4><pre>Watchers.<strong>Watcher</strong>(&quot;Watcher C&quot;)<br>.<strong>Board</strong>(&quot;Board A&quot;, board =&gt; <br>{ <br>	board.<strong>Card</strong>(&quot;Card A&quot;, card =&gt; <br>	{<br>		card.<strong>Container</strong>(&quot;Container A&quot;)<br>			.<strong>AddActionButton</strong>(&quot;Click me&quot;, () =&gt; Debug.<strong>Log</strong>(&quot;Hello World&quot;));<br><br>		card.<strong>Container</strong>(&quot;Container B&quot;)<br>			.<strong>Add</strong>(&quot;GeneralInfoKey&quot;, <strong>new</strong> <strong>Label</strong>(&quot;General Info&quot;), label =&gt; label.style.color = Color.yellow)<br>			.<strong>AddProperty</strong>(<strong>nameof</strong>(SomeValue), <strong>this</strong>, x =&gt; x.SomeValue, x =&gt; SomeValue = x);<br>	});<br><br>	board.<strong>Card</strong>(&quot;Card B&quot;);<br>});</pre><h3>Watcher UI Elements</h3><h4>Selector Buttons</h4><p>Extension that adds button which will find your object in the scene hierarchy. It is setting Selection.activeObject under the hood</p><pre>.<strong>AddSelectorButton</strong>($&quot;Select {gameObject.name}&quot;, gameObject)</pre><h4>Action Buttons</h4><p>Extension that adds button with an action. Really useful for testing!</p><pre>.<strong>AddActionButton</strong>(&quot;Click me&quot;, () =&gt; Debug.<strong>Log</strong>(&quot;Hello World&quot;));</pre><h4>Properties</h4><p>Add various kind of properties to your UI elements</p><p>SerializedProperty</p><p>Serialized properties can be invoked on UnityEngine.Objects like Components/MonoBehaviours/ScriptableObjects. It will be displayed in the same way as in the inspector.</p><pre>.<strong>AddSerializedProperty</strong>(<strong>this</strong>, x =&gt; x.SomeClass)</pre><p><strong>Property</strong></p><p>Normal properties can be added through few handy overloads. Under the hood every property is a field from UI Elements that has been created for certain types like ints, floats, bools, Vector2s, Vector3s</p><p>The most generic way:</p><p>1) Getter/Setter</p><p>It will observe every value changed of a selected property</p><pre>.<strong>AddProperty</strong>(&quot;PropertyName&quot;, <strong>this</strong>, x =&gt; x.SomeValue, x =&gt; SomeValue = x)</pre><p>.AddProperty(1, 2, 3, 4)</p><p>1 — display name of the property<br>2 — property context, for example class where it is used<br>3 — getter from the context<br>4 — setter for the property. Is not required, but if you want to have two way binding you have to use it.</p><p>2) Observable way</p><pre>.<strong>AddProperty</strong>(<strong>nameof</strong>(ReactiveProperty), ReactiveProperty);</pre><p>.AddProperty(1, 2)</p><p>1 — display name of the property<br>2 — IReactiveProperty / IObservable</p><h3>Styling</h3><h4><a href="https://docs.unity3d.com/Manual/UIE-USS.html">USS</a></h4><p>There are two ways of styling your watchers. The first one is to use classic stylesheets</p><p>RMB on active folder -&gt; Create -&gt; Watchers Stylesheet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*4glD_XEdwoZu5IXnnjFr2A.png" /></figure><p>It will create base stylesheet with initial setup that you can work on.</p><p>Next create initializer script somewhere in your solution and point it to the Path where you have created your Stylesheet.</p><pre><strong>public</strong> <strong>class</strong> <strong>WatcherInitializer</strong><br>{<br>    [<strong>RuntimeInitializeOnLoadMethod</strong>(RuntimeInitializeLoadType.AfterAssembliesLoaded)]<br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>Initialize</strong>()<br>    {<br>        Watchers.EditorStylePath = &quot;Assets/MyStyles.uss&quot;;<br>    }<br>}</pre><h4>Inline styles</h4><p>Watcher cards and boards inherits from VisualElements so you can set inline styles like so</p><pre>element.style.color = Color.green;</pre><p>In case you want to use fluent API, watcher elements have their own callbacks</p><pre>.<strong>Property</strong>(&quot;SomeValue&quot;, <strong>this</strong>, x =&gt; x.SomeValue, x =&gt; SomeValue = x).<strong>Configure</strong>(field =&gt; field.style.borderWidth = 5);</pre><p>or shorter version:</p><pre>.<strong>Property</strong>(&quot;SomeValue&quot;, <strong>this</strong>, x =&gt; x.SomeValue, x =&gt; SomeValue = x, field =&gt; field.style.borderWidth = 5);</pre><pre>Watchers<br>	.<strong>Watcher</strong>()<br>	.<strong>Board</strong>()<br>	.<strong>Card</strong>(&quot;PRO CARD&quot;, card =&gt; <br>	{<br>		card.Title.style.color = Color.yellow;<br>		card.style.backgroundColor = Color.blue;<br>	})</pre><h3>Unity Examples</h3><p>All code samples can be found on our GitHub <a href="https://github.com/GbrosGames/Tools?path=Assets/Watchers">page</a></p><h3><a href="https://github.com/GbrosGames/Tools/blob/main/Assets/Watchers/Examples~/Example%201/SomeComponent.cs">Example 1</a></h3><h3>Where To Go From Here</h3><p><a href="https://gbrosgames.github.io/posts/UniRx-PowerObservables/">PowerObservables</a></p><h3>Resources</h3><p><a href="https://github.com/neuecc/UniRx">UniRx Library</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549b6cb73eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UniRx — PowerObservables]]></title>
            <link>https://medium.com/@gbrosgames/unirx-powerobservables-f709069def1b?source=rss-7f35175f9e43------2</link>
            <guid isPermaLink="false">https://medium.com/p/f709069def1b</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[power-observables]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Gbros Games Studio]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 17:32:38 GMT</pubDate>
            <atom:updated>2022-05-13T17:49:29.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>UniRx — PowerObservables</h3><p>[Intermediate] [MiniSeries]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2RS45J71xqtGhd0YXV7og.png" /></figure><h3>Prerequisites</h3><ul><li>Familiar with Observer pattern</li><li>Hands on any Rx library</li></ul><h3>Introduction</h3><p>PowerObservables are set of time-based operations with ability to pause and possibility to manage tick freqeuency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70s-avP-TB6Pu9PfbyVsUg.png" /></figure><h3>Why Power Observables</h3><ul><li>Easy access to time-based operations</li><li>Timers / Countdowns based on TimeSpans</li><li>Ability to pause an observable using another observable (i.e. BoolReactiveProperty)</li></ul><h3>Power Observables</h3><ul><li>Countdown — an observable sequence that produces a differed time value for certain duration with ability to pause and resume. Completes when there is no time left.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*XEtPJonU3rEa_Vp6.gif" /></figure><p>It’s pretty usefull when it comes to</p><ul><li>Limit time in Arcade Games</li><li>Countdown before race start when you want to prompt “3, 2, 1, GO”</li><li>Damage overtime — every tick deal 10 damage to player, on complete remove debuff</li></ul><pre>PowerObservable.Countdown(Time)<br>                .Subscribe(OnTick, OnComplete)<br>                .AddTo(this);</pre><p><em>Sequence: Countdown(3) → 2 → 1 → done with 3rd tick</em></p><ul><li>TimerInterval — an observable sequence that produces a value after each period for certain duration with ability to pause.</li></ul><pre>PowerObservable.TimerInterval(Time)<br>                .Subscribe(OnTick, OnComplete)<br>                .AddTo(this);</pre><p><em>Sequence: TimerInterval(3) → 1 → 1 → done with 3rd tick</em></p><ul><li>CountedInterval — returns an observable sequence with aggregated time since subscribe with pause option</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Q2kycPxP81ZEBt5o.gif" /></figure><p><em>Sequence: CountedInterval() → 1 → 2 → 3 → 4 → 5…</em></p><ul><li>TimerCountedInterval — returns an observable sequence with aggregated time since subscribe. Lasts for certain duration. It’s the same concept as Countdown but reversed. Instead times go up from zero. It completes after certain duration.</li></ul><p><em>Sequence: TimerCountedInterval(3) → 1 → 2 → done with 3rd tick</em></p><h3>How To Use</h3><p>Simple use case scenario below:</p><pre>var pause = new BoolReactiveProperty(); // create UniRx ReactiveProperty to manage pause<br><br>PowerObservables.CountedInterval(pause, tick: 1f) // you can provide the freqeuency of ticks<br>		.Subscribe(time =&gt; 	<br>                { <br>				// every tick <br>				// 00:00 ...<br>				// 00:01 ...<br>				// 00:02<br>		})<br>		.AddTo(this); <br><br>pause.Value = true; // interval will stops<br>pause.Value = false; // interval will resume from previous point</pre><h3>Unity Installation</h3><p>Since unity doesn’t support git dependencies in package.json you have to <a href="https://github.com/neuecc/UniRx#upm-package">install UniRx</a> manually.</p><p>Edit manifest.json file in your Unity Packages directory</p><pre>{<br>	&quot;dependencies&quot;: {<br>	&quot;com.gbros.tools.unirx.powerobservables&quot;: &quot;[&lt;https://github.com/GbrosGames/Tools.git?path=Assets/UniRx/PowerObservables&gt;](&lt;https://github.com/GbrosGames/Tools.git?path=Assets/UniRx/PowerObservables&gt;)&quot;,<br>	&quot;com.neuecc.unirx&quot;: &quot;[&lt;https://github.com/neuecc/UniRx.git?path=Assets/Plugins/UniRx/Scripts&gt;](&lt;https://github.com/neuecc/UniRx.git?path=Assets/Plugins/UniRx/Scripts&gt;)&quot;<br>  }<br>}</pre><h3>Unity Examples</h3><p>All code samples can be found on our GitHub <a href="https://github.com/GbrosGames/Tools/tree/main/Assets/UniRx/PowerObservables">page</a>.</p><h3>Example 1 — Counted Interval</h3><p>This example shows how to create Interval observable that will return TimeSpan in the cumulative way. It shows the way of refreshing the UI. It also shows use case for BoolReactiveProperty from UniRx library to manage pause/resume functionality.</p><h3>Example 2 — Countdown</h3><p>This example shows how to create, restart and refresh Countdown and how to manage subscription and completion methods in observable.</p><h3>Where To Go From Here</h3><ul><li><a href="http://www.gbrosgames.com/posts/UniRx-Series-Part-1-MessageBroker">MessageBroker</a></li></ul><h3>Resources</h3><ul><li><a href="https://github.com/neuecc/UniRx">UniRx Library</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f709069def1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UniRx Series — [Part 1] — MessageBroker]]></title>
            <link>https://medium.com/@gbrosgames/unirx-series-part-1-messagebroker-8d9c4b4581e4?source=rss-7f35175f9e43------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d9c4b4581e4</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Gbros Games Studio]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 17:25:47 GMT</pubDate>
            <atom:updated>2021-07-21T17:25:47.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>UniRx Series — [Part 1] — MessageBroker</h3><p>[Intermediate]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00H8tEaA6NxmvX1gHnNmqw.png" /></figure><p>This series will be highly related to <a href="https://github.com/neuecc/UniRx">UniRx</a> library.</p><h3>Prerequisites</h3><ul><li>Familiar with Observer pattern</li><li>Hands on any Rx library</li></ul><h3>Introduction</h3><p><a href="https://github.com/neuecc/UniRx/blob/master/Assets/Plugins/UniRx/Scripts/Notifiers/MessageBroker.cs">MessageBroker</a> is an in-memory publish/subscribe messaging system that provides event-driven, decoupled architecture in order to increase performance, reliability and scalability of your Unity application.</p><p>It has three main components:</p><ul><li>Publisher of message — allows message to be broadcasted to the different parts of the application</li><li>Receiver of message — receives the message produced by the publisher.</li><li>MessageBroker — an orchestrator of all events.</li></ul><p>We will be using UniRx implementations. The API contains two main methods:</p><pre>IObservable&lt;TMessage&gt; MessageBroker.Default.Receive&lt;TMessage&gt;<br></pre><pre>void MessageBroker.Default.Publish&lt;TMessage&gt;</pre><p>Where TMessage is a type we want to publish/receive.</p><p>Receive method returns an observable, so we have to Subscribe in order to be notified by MessageBroker.</p><p>Let’s go through a simple scenario, where we will aim to propagate a message across the game that something important has happened.</p><h3>Message</h3><p>First let’s create our message class.</p><p>To emphasize that our message can be anything, we will call our class GameEvent. Different approach surrounding types of objects that can be used here is described later in the article (see IMessage).</p><p>To keep things simple, our GameEvent class will contain only Name property. We will also define two distinct types of our GameEvent (Dragon and HappyHours), which we will be able to reference later.</p><pre>public class GameEvent<br>{<br>	public const string Dragon = nameof(Dragon);<br>	public const string HappyHours = nameof(HappyHours);<br><br>	public string Name { get; }<br>	public GameEvent(string name)<br>	{<br>		Name = name;<br>	}<br>}</pre><p><em>TIP — It’s good to avoid magic numbers and hard coded strings. One of the easiest way to do that is to create const properties and use “nameof()”. We can easily reference this value later.</em></p><h3>Publisher</h3><p>After that let’s publish a message:</p><pre>public class Player: MonoBehaviour<br>{<br>	// when the dragon appears in range of the player<br>	void OnDragonNoticed()<br>	{<br>		MessageBroker.Default.Publish(new GameEvent(GameEvent.Dragon));<br>	}<br>}</pre><h3>Receivers</h3><p>Now each game object that is interested in certain event has to subscribe through a receiver of our message object class:</p><pre>public class Villager : MonoBehaviour<br>{<br>	void Awake()<br>	{<br>		MessageBroker.Default<br>			.Receive&lt;GameEvent&gt;()<br>			.Where(x =&gt; x.Name == GameEvent.Dragon)<br>			.Subscribe(_ =&gt; Flee()).AddTo(this);<br>	}<br><br>	void Flee()<br>	{<br>		// run as fast as possible<br>	}<br>}</pre><p>This is where familiarity with Rx library comes in handy. As you can see, we do not have to create instance of our receiver (which is an observable). We simply query for our receiver message class type (of GameEvent), to filter out our game events by name, to finally subscribe against them. AddTo() method is crucial here: it links our subscription with Villager game object instance, ensuring proper life cycle when Villager gets destroyed (there are other methods that we could use to manage lifecycle, I left description on few of them in the good practices section).</p><p>Now all villagers on the map will know that dragon is coming and they will run away to save their poor lives!</p><p>Another good example is to use the same event in the AudioPlayer:</p><pre>public class AudioPlayer: MonoBehaviour<br>{<br>    void Awake()<br>    {<br>        MessageBroker.Default<br>		.Receive&lt;GameEvent&gt;()<br>		.Where(x =&gt; x.Name == GameEvent.Dragon)<br>		.Subscribe(_ =&gt; PlayGlobalEventSound())<br>		.AddTo(this);<br>    }<br>}</pre><p>Thanks to this our AudioPlayer component will also be notified about the same events and will play some intense music to inform the player that something important has happened.</p><p>To summarize: when Player will notice the dragon, MessageBroker will publish GameEvent, and all Receivers will be notified.</p><p>What is more, our subscribers (Villager and AudioPlayer components) which are listening to the same Dragon event, both will react in their own unique way.</p><p>With this approach, we successfully decoupled our logic. Player MonoBehaviour don’t have to track any references to Villagers or AudioPlayer — and vice versa. Logic that we provided will be triggered automatically, so either Player, who is responsible here for noticing the dragon, or Villager or even AudioPlayer has to know about each other.</p><p>Obviously there is many ways of handling such events. The one, that we just went through, is filtering observable by name.</p><p>Now lets have a look at another good approach, which is to create a class for each event. Lets stay with the same context and declare DragonGameEvent and HappyHoursGameEvent (both inheriting from our GameEvent class):</p><pre>public class DragonGameEvent : GameEvent { }</pre><pre>public class HappyHoursGameEvent : GameEvent { }</pre><p>This approach is making our solution to work on concrete types instead of string based names.</p><p>Our Audio Player can now directly listen for the same event, but code gets simpler:</p><pre>public class AudioPlayer: MonoBehaviour <br>{ <br>    void Awake() <br>    { <br>        MessageBroker.Default.Receive&lt;DragonGameEvent&gt;(_ =&gt; PlayDragonSound()); <br>    } <br>}</pre><p>Alternatively, in case we need to identify more events or process additional data from event object, we can use pattern matching to identify what event has occurred:</p><pre>public class AudioPlayer: MonoBehaviour <br>{ <br>    void Awake() <br>    { <br>        MessageBroker.Default<br>		.Receive&lt;GameEvent&gt;(message =&gt; PlaySound(gameEvent))<br>		.AddTo(this);  <br>    } <br><br>    void PlaySound(GameEvent gameEvent)<br>    {<br>        if (gameEvent is DragonGameEvent dragonEvent)<br>        {<br>            // play dragon event sound<br>        }<br>    }<br>}</pre><p>This wraps up basics and idea behind them.</p><p>If you want to learn more, below is ours, more practical, approach to utilize power hidden behind the MessageBroker.</p><h3>IMessage</h3><p>We like to keep all requests as ScriptableObjects. Most of our Messages inherits from base Message class and implements simple IMessage interface, as below:</p><pre>/// &lt;summary&gt;<br>/// Base class for ScriptableObject requests.<br>/// If you want to call MessageBroker from MonoBehaviours, call them directly -&gt; Message.Create()<br>/// ScriptableObject can&#39;t have constructors, try to add every Message through static Create method.<br>/// &lt;/summary&gt;<br>public abstract class Message: ScriptableObject, IMessage<br>{<br>    [Button]<br>    [HideInEditorMode]<br>    public void Publish()<br>    {<br>        MessageBroker.Default.PublishMessage(this);<br>    }<br>}</pre><p>If only Unity would support default interfaces we would be able to ignore base ScriptableObject class and use interface only. But for now we have to split it into base class and an interface.</p><pre>public interface IMessage<br>{<br>    void Publish();<br>}</pre><p>Below is few useful extensions, so we don’t have to put Type into the angle brackets &lt;&gt; all the time.</p><pre>public static class MessageBrokerExtensions <br>{ <br>    public static IObservable&lt;T&gt; ReceiveMessage&lt;T&gt;(this IMessageBroker messageBroker) <br>    =&gt; messageBroker.Receive&lt;IMessage&gt;().OfType&lt;IMessage, T&gt;(); <br><br>    public static void PublishMessage&lt;T&gt;(this IMessageBroker messageBroker, T message) <br>where T : IMessage <br>    =&gt; messageBroker.Publish&lt;IMessage&gt;(message); <br>}</pre><p>Thanks to this setup, we don’t have to call Receive of Type every time we want to handle IMessage, of the given Type.</p><p>It is a small improvement but it really makes life easier. To visualize the difference, this is before:</p><pre>MessageBroker.Default.Publish&lt;IMessage&gt;(message); // message.Publish();<br>MessageBroker.Default.Receive&lt;IMessage&gt;().OfType&lt;IMessage, GameEvent&gt;();</pre><p>and after the changes:</p><pre>MessageBroker.Default.PublishMessage(message); // message.Publish();<br>MessageBroker.Default.ReceiveMessage&lt;GameEvent&gt;();</pre><p>Additional benefit to using ScriptableObjects and a base class is keeping MessageBroker abstraction well separated. So if we would like to switch to different implementation or concept, we can easily do it in one place.</p><p>Clean and simple right?</p><p>After all this changes, our GameEvent message class, from the original example, would now look like this:</p><pre>public class GameEvent : Message<br>{<br>    public const string Dragon = nameof(Dragon);<br>    public const string HappyHours = nameof(HappyHours);<br><br>    [SerializeField] string name = default;<br>    public string Name =&gt; name;<br><br>    public static GameEvent Create(string name)<br>    {<br>        var instance = CreateInstance&lt;GameEvent&gt;();<br>        instance.name = name;<br>        return instance;<br>    }<br>}</pre><p><em>TIP — ScriptableObjects can’t have constructors. Elegant way to bypass this, is adding static Create method and assigning values, as we usually do in the constructors.</em></p><p>And our Player class, like this</p><pre>public class Player: MonoBehaviour<br>{<br>	// when the dragon appears in range of the player<br>	void OnDragonNoticed()<br>	{<br>		// before: <br>		// MessageBroker.Default.Publish(new GameEvent(GameEvent.Dragon));<br>		// now:<br>		GameEvent.Create(GameEvent.Dragon).Publish();<br>	}<br>}</pre><h3>Custom Editor</h3><p>There is one more improvement to the whole thing, that is really worth mentioning.</p><p>If you are using Odin Inspector (which we highly recommend), you can just put [Button] attribute above Publish() method in our base class. This will enable you to easily propagate Messages along all Receivers from the Inspector in the play mode.</p><p>If you don’t have <a href="https://odininspector.com/">Odin Inspector</a> (again, which we really recommend), you can use the following code:</p><pre>[CustomEditor(typeof(Message), editorForChildClasses: true)] <br>public class Messageditor : Editor <br>{ <br>    public override void OnInspectorGUI() <br>    { <br>        DrawDefaultInspector(); <br>        if (!Application.isPlaying) return; <br>        if (!(target is IMessage message)) return; <br>        if (GUILayout.Button(nameof(IMessage.Publish))) <br>        { <br>            message.Publish(); <br>        } <br>    } <br>}</pre><p>Thanks to all of this, we can now create Message assets in our project, and test our system by clicking “Publish” button to debug certain functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*PXTxVhWiEwpUEaEV.png" /></figure><p>It helps us to keep our messages organized. Debugging is easy. And whole game development process is much more comfortable.</p><h3>Utilities</h3><p>You can also create many utilities based on ScriptableObjects and the Messages system.</p><p>Another utility which is pretty handy is component that allows you to activate GameObject after certain message is received:</p><pre>/// &lt;summary&gt;<br>/// Activates game object when receive Message <br>/// &lt;/summary&gt;<br>public abstract class ActivateOnMessage&lt;T&gt; : MonoBehaviour where T : Message<br>{<br>	// the message itselft so we can reference it from the inspector<br>        [SerializeField] protected T message;<br><br>	// condition that has to be met to activate an object<br>	// this declaration allows to change base function in case different filtration is needed<br>        protected virtual Func&lt;T, bool&gt; predicate =&gt; <br>					incomingMessage =&gt; <br>					incomingMessage.GetType() == message?.GetType();<br><br>        public virtual void Awake()<br>        {<br>            this.gameObject.SetActive(false);<br><br>            MessageBroker.Default.ReceiveMessage&lt;T&gt;()<br>                .Where(predicate)<br>                .Subscribe(x =&gt; gameObject.SetActive(true))<br>                .AddTo(this);<br>        }<br>}<br><br>// general class that will activate object when any referenced message of type Message is received<br>public class ActivateOnMessage : ActivateOnMessage&lt;Message&gt; { }</pre><p>When attached to a GameObject, above component looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*ukyUrdD7iCjvjjwm.png" /></figure><p>Good place to take advantage of the above utility is to manage our game loop. Lets say we have a game manager that is propagating game loop events like <em>GameStart</em>, <em>GameEnd</em>, <em>GameWon</em>, <em>GameLost</em> etc. With our utility tool we can easily Activate / Deactivate certain GameObjects by adding ActivateOnMessage component to GameObjects associated with our game loop.</p><p>What’s more, we have marked our ActivateOnMessage class as Generic. This gives us ability to switch base Type and to override predicates in more complex scenarios.</p><p>For example if we add ActivateOnMessage component we can reference any kind of Message as our base predicate is comparing only type of incoming message and the value referenced from the inspector:</p><pre>protected virtual Func&lt;T, bool&gt; predicate =&gt; incomingMessage =&gt; <br>incomingMessage.GetType() == message?.GetType();</pre><p>In order to filter GameEvents, like in our initial examples (by name), now we only need to simply create a class that inherits from ActivateOnMessage. Through usage of generic types we can reference any properties and create custom conditions:</p><pre>public class ActivateOnGameEvent : ActivateOnMessage&lt;GameEvent&gt;<br>{<br>		protected override Func&lt;GameEvent, bool&gt; predicate =&gt;<br>                                                         incomingMessage =&gt;<br>                                                         incomingMessage.Name == message.Name;<br>}</pre><p>And component like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*r49hrOTJv_9G_qyr.png" /></figure><p>That being said, in 90% of cases, we simply use ActivateOnMessage and instead do filtering through properties, we filter them by type:</p><pre>public class DragonGameEvent : GameEvent { }</pre><pre>public class HappyHoursGameEvent : GameEvent {}</pre><p>Key take-away here is that it is much easier to maintain strongly typed messages. Otherwise you would end up hardcoding tons of settings in the inspector of many GameObjects scattered across whole solution. Which is not scaling well and is prone to human errors.</p><h3>Unity Code Samples</h3><p>All code samples can be found on our GitHub <a href="https://github.com/GbrosGames/Blog/tree/main/Assets/UniRx/MessageBroker">page</a>.</p><p><strong><em>Example 1 — Color Switcher</em></strong></p><p>In this example we will use MessageBroker as simple example of code decoupling.</p><p>We will create :</p><ul><li>ColorSwitchMessage — message as a request to switch color</li><li>ColorGenerator component, that will generate new ColorSwitchMessage with random color whenever space bar is pressed</li><li>ColorSwitcher — object that will switch its color whenever receives ColorSwitchMessage</li></ul><p><strong><em>Example 2 — Color Switcher with ScriptableObject request messages</em></strong></p><p>In this example we will improve our code and extract Message into ScriptableObject.</p><p><strong><em>Example 3 — Zone Change</em></strong></p><p>In this example we will see how to manage and decouple Game logic from UI by using Messages.</p><p>We will extract abstraction for our Messages and use IMessage class.</p><p><strong><em>Example 4 — Activate on Message</em></strong></p><p>In this example we will create generic components to activate messages of given type.</p><p>We will create countdown that publishes Game Start Message and activates the Player with utility component.</p><h3>Good Practices</h3><p>Lastly, lets make notes around few good practices that are worth mentioning here:</p><ul><li><em>It’s good to avoid magic numbers and hard coded strings. One of the greatest way is to create const property and use “nameof()”. We can easily reference this value later.</em></li><li><em>ScriptableObjects can’t have constructors. We can replace it in elegant way by creating static Create method and assign values as usual in constructors.</em></li><li>Lifecycle: r<em>emember to dispose subscriptions of your observables by using TakeWhile, TakeUntil, TakeUntilDestroy and TakeUntilDisable or simply add .AddTo(this) when you are in MonoBehaviour to prevent execution if component is destroyed that may leading to unexpected behaviours</em></li></ul><h3>Where to go from here</h3><p>This is first part of the article about UniRx. If you are interested, be sure to check next part that will cover in details the monitors.</p><p>All related scripts (and more!) can be found in our examples <a href="https://github.com/GbrosGames/Blog">repository</a>, so please give it a try!</p><p>Finally If you want to do more reading check resources section!</p><h3>Resources</h3><ul><li><a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">The introduction to Reactive Programming you’ve been missing</a></li><li><a href="http://introtorx.com/">Practical Rx Training</a></li><li><a href="https://github.com/neuecc/UniRx">UniRx Library</a></li><li><a href="https://github.com/reactivemanifesto/reactivemanifesto">Reactive manifesto</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d9c4b4581e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateless in Unity]]></title>
            <link>https://medium.com/@gbrosgames/stateless-in-unity-8a0f6db30307?source=rss-7f35175f9e43------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0f6db30307</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[stateless]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[Gbros Games Studio]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 15:53:32 GMT</pubDate>
            <atom:updated>2021-06-16T15:53:32.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prerequisites</h3><ul><li>Familiar with state pattern</li><li>Hands on events</li><li>Hands on generics</li></ul><h3>Introduction</h3><p>We were looking for lightweight solution for managing state of entities in Unity. We placed our bet on Stateless.NET library that we used previously during development of .NET Applications. It’s a nice and lightweight library under <a href="https://tldrlegal.com/license/apache-license-2.0-%28apache-2.0%29">Apache 2.0 License</a>.</p><h3>Why stateless?</h3><ul><li>Flexible</li><li>Lightweight</li><li>Hierarchical States</li><li>Possibility to reenter the state</li><li>Entry/Exit and Activation events</li><li>Guard clauses — for easy rules definition</li><li>Graph preview</li><li>Easy to read and maintain</li></ul><h3>Unity Installation</h3><p>Open NuGet package manager and search for <a href="https://github.com/dotnet-state-machine/stateless">Stateless</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5c2SuRk_B1qW_TN10qHZA.png" /></figure><p>After installation, copy Stateless.dll and Stateless.xml from <em>YourProject\Packages\Stateless.5.1.2\lib\netstandard2.0</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*cQKlPHbjzCjZqSPxd8OLXw.png" /></figure><p>Create folder for external, non-unity packages in Assets directory. It may be something like</p><pre>\Assets\Libraries\Stateless\</pre><p>and paste files there.</p><p>Now we are ready to go! :)</p><h3>How To Use</h3><p>Let’s create our Chest class and define our Trigger and State types:</p><pre>public class Chest : MonoBehaviour<br>{<br>        public enum State { Opened, Closed }<br>        public enum Trigger { Open, Close }<br>        ...<br>}</pre><p>Basic approach is to define representation of State as Enums, but thanks to generic types it can be everything, even MonoBehaviours.</p><p>It’s also good to define states and triggers directly in the class so we will avoid possibility of name duplication while creating our state machines. After that we can create our StateMachine. Let’s do it in Awake method.</p><pre>private StateMachine&lt;State, Trigger&gt; stateMachine;<br><br>private void Awake()<br>{<br>        stateMachine = new StateMachine&lt;State, Trigger&gt;(State.Closed);<br><br>        stateMachine<br>            .Configure(State.Opened)<br>            .OnEntry(OnChestOpened)<br>            .Permit(Trigger.Close, State.Closed);<br><br>        stateMachine<br>            .Configure(State.Closed)<br>            .OnEntry(OnChestClosed)<br>            .Permit(Trigger.Open, State.Opened);<br>}</pre><p>We have to call Configure method on every state to set up rules and relations between our states. After that we can define what actions can be performed during each state. Most common methods used during configuration for state machines are:</p><ul><li>OnEntry / OnExit — accepts Action which will be triggered on state enter / exit</li><li>OnEntryFrom — accepts Action which we want to perform after a transition from a certain state</li><li>Permit — the main method where we specify a valid state transition based on a trigger</li><li>PermitIf — as above with so called Guard (boolean function)</li><li>SubstateOf — method which sets parent state</li></ul><p>Lets look at the following example, where we are configuring state Opened and we are permitting Trigger Close to be called, after which state machine will transition its state to Closed:</p><pre>stateMachine<br>    .Configure(State.Opened)<br>    .Permit(Trigger.Close, State.Closed);</pre><p>Next we will configure state Closed. This time with the use of PermitIf . It is almost the same as above Permit function, but with ability to set up the Guard Clause — which will act as a Rule that will tell us whether we can enter triggered state or not:</p><pre>stateMachine<br>    .Configure(State.Closed)<br>    .PermitIf(Trigger.Open, State.Opened, () =&gt; player.HasEpicKeyInInventory());</pre><p>Lastly lets use SubstateOf — method which allows us to define hierarchy of States. We will use it for locked state, and we will set it as a sub-state of state closed:</p><pre>stateMachine<br>    .Configure(State.Locked)<br>    .SubstateOf(State.Closed)<br>...</pre><p>To check in which sate our machine currently is, we can call IsInState method. But this check also honours state hierarchy. So if our state machine would be in State.Locked and we would do check for State.Closed</p><pre>stateMachine.IsInState(State.Closed);</pre><p>the answer would be true.</p><p>Ok now lets see how we can harness benefits of using state machines! But first lets summarize what we did and what it gives us:</p><ul><li>We have created state machine for our Chest</li><li>We have described that at any time Chest enters the state Opened the OnChestOpened action will be invoked</li><li>We have also permitted our Trigger.Close to happen with destination state of Closed</li></ul><p>As you can see we didn’t write a single if statement here. For everyone that loves “clean code” or “less code” approach its already huge benefit.</p><p>Now let explore what potential advantages it gives us when we are constructing complicated state machines.</p><p>First of all it minimizes conditional complexity and eliminating the need for if and switch statements.</p><pre>private void OnChestClosed()<br>{<br>      // play close animation<br>      // play close sound<br>}<br>private void OnChestOpened()<br>{<br>      // play open animation<br>      // play open sound<br>}</pre><p>Secondly we can easily, extend the API for our Chest class by exposing public methods with ability to trigger its state changing logic:</p><pre>public void Open()<br>{<br>    if (!stateMachine.CanFire(Trigger.Open)) return;<br>    stateMachine.Fire(Trigger.Open);<br>}<br><br>public void Close()<br>{<br>    if (!stateMachine.CanFire(Trigger.Close)) return;<br>    stateMachine.Fire(Trigger.Close);<br>}</pre><p>Please note that before firing specific trigger, we are validating if we have a permission to fire this trigger from current state.</p><p>Firing a trigger that does not have an allowed transition associated with it will cause an exception to be thrown. To prevent that, simply register some default behaviour and override exception through OnUnhandledTrigger() method:</p><pre>stateMachine.OnUnhandledTrigger((state, trigger) =&gt; <br>{ <br>    Debug.Log($&quot;Unhandled trigger {trigger} can&#39;t befired from state {state}&quot;); <br>});</pre><p>Last thing that is really great about stateless is that your state machine can be visualized as a graph. Be sure to check Samples section below to learn more and get info where to find some code examples!</p><h3>Graph Preview</h3><p>The big advantage of using Stateless .NET is that you can easily visualize your state machine. To serialize your state machine to standard text-based <a href="https://en.wikipedia.org/wiki/DOT_%28graph_description_language%29">DOT</a> format, you have to call stateMachine GetInfo() method:</p><pre>var graphVisualization = UmlDotGraph.Format(stateMachine.GetInfo());</pre><p>Copy graphVisualization variable value and paste it on the <a href="http://www.webgraphviz.com/">here </a>— to see how the graph looks like. Obviously, if someone deems it necessary, this can be easily incorporated into unity through the custom editor script.</p><h3>Unity Code Samples</h3><p>All code samples can be found on our GitHub <a href="https://github.com/GbrosGames/Blog?path=Assets/Stateless">page</a>.</p><p><strong><em>Example 1 — Chest</em></strong></p><p>The chest example with Key Code enum as a trigger. It works like a toggle. Whenever we press a Space bar the chest will open if it’s closed or will close if it’s opened. It’s the most simplistic example that shows us base usage of Stateless library.</p><p><strong><em>Example 2 — Chest</em></strong></p><p>In this example we take whole idea from Example 1 a step further and we add custom trigger to open and close our chest. It’s good practice to nest State and Trigger inside the subject class, so we can avoid the name conflicts in case of multiple states and triggers are present in our project. We can refer to Chest state or trigger enum by calling it Chest.State / Chest.Trigger.</p><p><strong><em>Example 3 — Chest</em></strong></p><p>In this example we will learn how to improve our code even further. We’ve exposed the public events that are triggered whenever the chest is open or closed. By doing that we have decoupled our animations from the Chest class itself. We’ve created the ChestAnimation component which is responsible just for playing animations. We do it cause It’s not the Chest component responsibility to do all of those things. Another key take-away — it’s good to subscribe to events in OnEnable / OnDisable methods:</p><pre>private void OnEnable()<br>{<br>    chest.ChestClosed += OnChestClosed;<br>    chest.ChestOpened += OnChestOpened;<br>}<br>private void OnDisable()<br>{<br>    chest.ChestClosed -= OnChestClosed;<br>    chest.ChestOpened -= OnChestOpened;<br>}</pre><p>Now we have fully modular solution. We can add another component like ChestSound, ChestParticles, ChestReward etc.</p><p><strong><em>Example 4 — Interactables </em></strong>— just to show what can be done better</p><p>In this example we have added simple Player and two chests with overlapping areas.</p><p>We have removed Update method, which was listening for input, from Chest — because it’s not the Chest responsibility to manage user input. Instead of this, we’ve created Input Monitor with only one job: to gather user input. With this approach we can easily connect or replace this input system to a different one.</p><p>We’ve also added Interaction Monitor. It is registering every Interactables that can be interacted with whenever Player enters an interaction area. We have also created IInteractable interface and we extended Chest API by implementing it.</p><p>With this approach we are able to extend our system with ease. For example we can implement interface IInteractable in other places like Loot, Levers, Doors, and our Interaction Monitor will pick those up and handle all the communication between those components.</p><h3>Good Practices</h3><p>Lastly, lets make notes around few good practices that are worth mentioning here:</p><ul><li><em>Nest enum States and Triggers inside the subject class to avoid name conflicts in your solution</em></li><li><em>If you are creating states as separated classes, pass stateMachine Controller class to the constructor</em></li><li><em>Subscribe to events inside OnEnable method, and unsubscribe them in OnDisable</em></li></ul><h3>Where to go from here</h3><p>In the incoming blog posts we will like to share more techniques, that we’ve found useful, while working with reactive state machines in our projects. We really hope that more developers can take benefit from using state machines and incorporate them into their toolbox.</p><p>All related scripts (and more!) can be found in our examples <a href="https://github.com/GbrosGames/Blog?path=Assets/Stateless">repository</a>, so please give it a try!</p><p>Finally If you want to do more reading check resources section!</p><h3>Resources</h3><ul><li><a href="https://github.com/dotnet-state-machine/stateless">Official Stateless Repository</a></li><li><a href="https://www.hanselman.com/blog/stateless-30-a-state-machine-library-for-net-core">Really good introduction to Stateless library by S. Henselman</a></li><li><a href="https://deviq.com/design-patterns/state-design-pattern">Great read about state pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0f6db30307" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>