<?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 SwiftRoll 🐦 on Medium]]></title>
        <description><![CDATA[Stories by SwiftRoll 🐦 on Medium]]></description>
        <link>https://medium.com/@swiftroll3d?source=rss-924a973c8941------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xf7iV5eVr-yBbZFttw0zBg.png</url>
            <title>Stories by SwiftRoll 🐦 on Medium</title>
            <link>https://medium.com/@swiftroll3d?source=rss-924a973c8941------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:38:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swiftroll3d/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[Singleton Alternatives in Unity C#]]></title>
            <link>https://medium.com/@swiftroll3d/singleton-alternatives-in-unity-c-05d608ed7fa2?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/05d608ed7fa2</guid>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 20:01:47 GMT</pubDate>
            <atom:updated>2024-04-23T23:22:24.724Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the Singleton Pattern?</h3><p>In short, the Singleton Pattern refers to a class that allows only one instance to exist at a time, which can be accessed statically by any other class</p><p>Its purpose is to solve the problem of finding and accessing one-instance classes in your project</p><p>It can look like this:</p><pre>public sealed class PlayerSingletonPlain<br>{<br>    private static PlayerSingletonPlain _instance;<br>    public static PlayerSingletonPlain Instance<br>    {<br>        get<br>        {<br>            if (_instance == null)<br>                _instance = new PlayerSingletonPlain();<br>            return _instance;<br>        }<br>    }<br><br>    public int Health { get; set; }<br>}</pre><p>Or like this if it’s MonoBehaviour:</p><pre>public sealed class PlayerSingletonMono : MonoBehaviour<br>{<br>    private static PlayerSingletonMono _instance;<br>    public static PlayerSingletonMono Instance<br>    {<br>        get<br>        {<br>            if (_instance == null)<br>            {<br>                _instance = new GameObject(&quot;SingletonMono&quot;).AddComponent&lt;PlayerSingletonMono&gt;();<br>                DontDestroyOnLoad(_instance.gameObject);<br>            }<br>            return _instance;<br>        }<br>    }<br><br>    public int Health { get; set; }<br>}</pre><p>And here’s an example of accessing a Singleton from another class:</p><pre>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    private void Start()<br>    {<br>        //plain<br>        _healthText.text = PlayerSingletonPlain.Instance.Health.ToString();<br><br>        //mono<br>        _healthText.text = PlayerSingletonMono.Instance.Health.ToString();<br>    }<br>}</pre><h3>Why Singleton can be considered Anti-Pattern</h3><p>While Singletons are a fast and easy way of accessing classes in your code, they have many downsides, which may snowball into architecture hell later, when a project gets bigger.</p><p>Here’s a brief list of reasons why Singletons may not be perfect solution for your project:</p><p><strong>Fundamental limitation to one instance<br></strong>For example, introducing multiplayer (even local like split-screen) will break functionality of all player-related singleton classes in the project, and resolving situations like this too late will require massive refactoring with architecture re-design.</p><p><strong>No Abstractions and Late-Binding<br></strong>Singleton doesn’t allow any usage of abstractions because you access the class by its direct type. Inheritance and changing implementations during runtime (Late-Binding) aren’t part of Singleton design.</p><p>For example you cannot swap two different implementations of IPlayerInput interface (one for keyboard+mouse and one for gamepad) when player connects a gamepad</p><p><strong>Hidden Dependencies<br></strong>Accessing dependencies by static access makes it hard to understand what dependencies a class has just by looking at it, because they’re hidden deep in the code of methods.</p><p>In comparison, dependencies stored in fields are easily visible at the top of the class file.</p><p><strong>Lack of Lifetime Control<br></strong>You have little to no lifetime control over singleton instances; they’re created when they’re first needed and destroyed only when the player exits the game. That can create difficulties for situations like game restarting or loading saves if singletons are used for in-game objects like Player.</p><p><strong>Unit-Tests<br></strong>Singletons also make unit-testing <strong>very</strong> difficult, which is important for certain situations and projects.</p><h3>Service Locator Alternative</h3><p>It is possible to resolve ‘No Abstractions’ problem of Singletons by using other pattern — Service Locator.</p><p>Service Locator can look like the following:</p><pre>public sealed class ServiceLocator<br>{<br>    private readonly static Dictionary&lt;Type, object&gt; _services = new Dictionary&lt;Type, object&gt;();<br><br>    public static void Register&lt;T&gt;(T service)<br>    {<br>        _services[typeof(T)] = service;<br>    }<br><br>    public static T Get&lt;T&gt;()<br>    {<br>        return (T) _services[typeof(T)];<br>    }<br>}</pre><p>Here’s an example of using it:</p><pre>public interface IPlayer<br>{<br>    public int Health { get; set; }<br>}<br><br>public sealed class Player : MonoBehaviour, IPlayer<br>{<br>    public int Health { get; set; };<br><br>    private void Awake()<br>    {<br>        ServiceLocator.Register&lt;IPlayer&gt;(this);<br>    }<br>}<br><br>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    private void Start()<br>    {<br>        _healthText.text = ServiceLocator.Get&lt;IPlayer&gt;().Health.ToString();<br>    }<br>}</pre><p>It solves part of Singleton’s problems:</p><ul><li>Abstractions and Late-Binding are possible</li><li>Manual lifetime control is possible, but it’s globally accessible</li><li>It resolves some problems with unit-testing: it’s possible to make Mock implementations, but if you run multiple tests in one run, previously created instances in service locator still exist, and you may need to manually clear them</li></ul><p>Also remember that it’s possible to get null reference when accessing a service that isn’t created, or just access wrong service type because of generics</p><h3>Dependency Injection (DI) Alternative</h3><p>To resolve all the problems that Singleton has, you can use Dependency Injection (DI) approach.<br>It’s designed around <strong>Composition Root</strong> class that establishes dependencies.</p><p>This is better illustrated with an example:</p><pre>public sealed class CompositionRoot : MonoBehaviour<br>{<br>    [SerializeField] private Player _playerPrefab;  //prefab for the player<br>    [SerializeField] private UIHealthBar _uiHealthBar;  //existing on the scene health bar<br><br>    private void Awake()<br>    {<br>        //create new player<br>        Player player = Instantiate(_playerPrefab);<br><br>        //init existing health bar to it<br>        _uiHealthBar.Init(player);<br>    }<br>}<br><br>public interface IPlayer<br>{<br>    public int Health { get; set; }<br>}<br><br>public sealed class Player : MonoBehaviour, IPlayer<br>{<br>    public int Health { get; set; }<br>}<br><br>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    private IPlayer _player;<br><br>    public void Init(IPlayer player)<br>    {<br>        _player = player;<br><br>        _healthText.text = _player.Health.ToString();<br>    }<br>}</pre><p>Also notice that dependencies that are established through [SerializeField] fields can be considered DI injected too.</p><p>Let’s see how it solves some of the real problems</p><p><strong>Having multiple Player instances<br></strong>To create multiple player instances, we only need to modify the composition root and adjust the UI for more than one health bar:</p><pre>public sealed class CompositionRoot : MonoBehaviour<br>{<br>    [SerializeField] private Player _playerPrefab;  //prefab for a player<br><br>    [SerializeField] private UIHealthBar _uiHealthBarPrefab;  //prefab for a health bar<br>    [SerializeField] private RectTransform _uiHealthBarsParent;  //parent for health bars<br><br>    private void Awake()<br>    {<br>        //first player<br>        //create new player<br>        Player player1 = Instantiate(_playerPrefab);<br><br>        //create new health bar<br>        UIHealthBar uiHealthBar1 = Instantiate(_uiHealthBarPrefab, _uiHealthBarsParent);<br>        uiHealthBar1.Init(player1);<br><br>        //second player<br>        //create new player<br>        Player player2 = Instantiate(_playerPrefab);<br><br>        //create new health bar<br>        UIHealthBar uiHealthBar2 = Instantiate(_uiHealthBarPrefab, _uiHealthBarsParent);<br>        uiHealthBar2.Init(player2);<br>    }<br>}</pre><p><strong>Managing Abstractions and Late-Binding<br></strong>Now let’s say that the game is multiplayer and we want second player to be different implementation of IPlayer:</p><pre>public sealed class PlayerMultiplayer : MonoBehaviour, IPlayer<br>{<br>    public int Health { get; set; }<br><br>    //... some multiplayer code that receives health from network<br>}<br><br>public sealed class CompositionRoot : MonoBehaviour<br>{<br>    [SerializeField] private Player _playerPrefab;  //prefab for a player<br>    [SerializeField] private PlayerMultiplayer _playerMultiplayerPrefab;  //prefab for a player from multiplayer<br><br>    [SerializeField] private UIHealthBar _uiHealthBarPrefab;  //prefab for a health bar<br>    [SerializeField] private RectTransform _uiHealthBarsParent;  //parent for health bars<br><br>    private void Awake()<br>    {<br>        //first player<br>        //create new player<br>        Player player1 = Instantiate(_playerPrefab);<br><br>        //create new health bar<br>        UIHealthBar uiHealthBar1 = Instantiate(_uiHealthBarPrefab, _uiHealthBarsParent);<br>        uiHealthBar1.Init(player1);<br><br>        //second player<br>        IPlayer player2;<br>        bool isMultiplayer = true; //check if it&#39;s multiplayer<br>        if (isMultiplayer)<br>        {<br>            //if multiplayer - create multiplayer player<br>            player2 = Instantiate(_playerMultiplayerPrefab);<br>        }<br>        else<br>        {<br>            //if not - create default player<br>            player2 = Instantiate(_playerPrefab);<br><br>        }<br><br>        //create new health bar<br>        UIHealthBar uiHealthBar2 = Instantiate(_uiHealthBarPrefab, _uiHealthBarsParent);<br>        uiHealthBar2.Init(player2);<br>    }<br>}</pre><p><strong>Unit-Testing<br></strong>Composing environment for unit-tests, making and passing Mock implementations of interfaces are easy to do with DI, but keep in mind that unit-test classes don’t have the possibility to use [SerializeField] fields, so in some cases other way of getting dependencies for compositing is needed.</p><h3>DI Injection Types</h3><p><strong>Construction Injection<br></strong>Most preferred way of injection when possible:</p><pre>public sealed class HealthLogger<br>{<br>    private IPlayer _player;<br><br>    public HealthLogger(IPlayer player)<br>    {<br>        _player = player;<br><br>        Debug.Log($&quot;Player health: {_player.Health}&quot;);<br>    }<br>}</pre><p>Unity’s MonoBehaviours cannot have constructors, to solve this problem you can write Init(..) method in MonoBehaviour inheritors:</p><pre>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    private IPlayer _player;<br><br>    //replacement for constructor<br>    public void Init(IPlayer player)<br>    {<br>        _player = player;<br><br>        _healthText.text = _player.Health.ToString();<br>    }<br>}</pre><p><strong>Property Injection<br></strong>Useful for situations when dependency is optional</p><pre>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    public IPlayer Player { get; set; }<br><br>    private void Update()<br>    {<br>        if (Player != null)<br>        {<br>            _healthText.text = Player.Health.ToString();<br>            _healthText.gameObject.SetActive(true);<br>        }<br>        else<br>        {<br>            _healthText.gameObject.SetActive(false);<br>        }<br>    }<br>}</pre><p><strong>Method Injection<br></strong>Can be used when dependency is needed only for certain method that’s being called from other classes</p><pre>public sealed class UIHealthBar : MonoBehaviour<br>{<br>    [SerializeField] private TextMeshProUGUI _healthText;<br><br>    public void UpdateHealth(IPlayer player)<br>    {<br>        _healthText.text = player.Health.ToString();<br>    }<br>}</pre><h3>DI Frameworks and Containers</h3><p>There are well-known open-source DI frameworks, and some are adapted for Unity, such as VContainer, Reflex and Zenject/Extenject.</p><p>They’re not required for implementing DI in your project, mostly they just provide convenient DI Container.</p><p>A DI Container is helpful tool to make it easier to write a Composition Root and pass dependencies. Especially it’s useful for big projects where there are many dependencies and it’s easy to become frustrated from manually handling them.</p><p>Remember that it’s a tool that still requires you to use it in a right way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05d608ed7fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Mistakes When Using Structs in C#]]></title>
            <link>https://medium.com/@swiftroll3d/avoiding-mistakes-when-using-structs-in-c-b1c23043fce0?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c23043fce0</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 14:31:19 GMT</pubDate>
            <atom:updated>2024-05-26T16:32:36.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Theory</h3><h4>Stack vs Heap</h4><p>Both the Stack and the Heap are complex topics. Here, I’ll provide only a brief and practical explanation.</p><p><strong>Stack<br></strong>The Stack is a “last in, first out” (LIFO) data structure with two core functions: adding data to the top of it (<strong>push</strong>) and returning data from the top of it (<strong>pop</strong>).<br>When you run your program it has small memory space that’s organized as a Stack. <br>- When you declare a variable inside a method it’s “<strong>pushed</strong>” onto the Stack.<br>- When you’re accessing that variable later it’s accessed based on its <strong>position </strong>on the Stack. <br>- When you’re returning from method, the memory pushed from that method is “<strong>popped</strong>”.</p><p>That also means that objects on the Stack <strong>generally</strong> have a <strong>short lifetime</strong>.</p><p><strong>Heap</strong><br>In short, the Heap is simply a large memory space inside the application’s memory space that’s provided for storing various types of data.<br><em>There is also a data structure called a Heap, but it is not connected to the memory heap.</em></p><p><strong><em>More info</em></strong><em><br>- Understanding the Stack and Heap in C# </em><a href="https://endjin.com/blog/2022/07/understanding-the-stack-and-heap-in-csharp-dotnet"><em>https://endjin.com/blog/2022/07/understanding-the-stack-and-heap-in-csharp-dotnet</em></a><em><br>- More technical details </em><a href="https://en.wikibooks.org/wiki/Memory_Management/Stacks_and_Heaps"><em>https://en.wikibooks.org/wiki/Memory_Management/Stacks_and_Heaps</em></a></p><h4>Reference type vs Value type</h4><p>Difference between Reference and Value time is specified in the ECMA-334 standard:</p><blockquote><em>Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter being known as objects.</em></blockquote><p>Generally that also means that <strong>Reference</strong> types are stored in the <strong>Heap</strong>, and <strong>Value </strong>types are stored in the <strong>Stack </strong>or as part of some object inside the Heap.</p><p>Let’s illustrate with simple examples:</p><pre>int a;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*G9JB5BcNkgb-JEkpLxbyhg.png" /><figcaption>Value type “int a” is stored in the Stack</figcaption></figure><pre>SomeClass someClass = new();<br><br>public class SomeClass<br>{<br>    public int a;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*gRhacmdOfIPL-ujEYXUG9g.png" /><figcaption>Value type “int a” is stored inside the Reference type</figcaption></figure><h3>Practice</h3><h4>Modification of fields</h4><p>The biggest difference between a class and a struct is noticeable when you modify their fields</p><pre>ClassExample();<br>StructExample();<br><br>void ClassExample()<br>{<br>    Console.WriteLine(&quot;Classes&quot;);<br>    <br>    SomeClass class1 = new();<br>    class1.x = 5;<br>    SomeClass class2 = class1;<br>    class1.x = 10;<br><br>    Console.WriteLine(class1.x);<br>    Console.WriteLine(class2.x);<br>}<br><br>void StructExample()<br>{<br>    Console.WriteLine(&quot;Structs&quot;);<br>    <br>    SomeStruct struct1 = new();<br>    struct1.x = 5;<br>    SomeStruct struct2 = struct1;<br>    struct1.x = 10;<br><br>    Console.WriteLine(struct1.x);<br>    Console.WriteLine(struct2.x);<br>}<br><br>public class SomeClass<br>{<br>    public int x;<br>}<br><br>public struct SomeStruct<br>{<br>    public int x;<br>}</pre><p>Exactly <strong>same code</strong> for the class and for the struct. Let’s check the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*7C8FwLAirB4Du2KyWftgtg.png" /><figcaption>Console output</figcaption></figure><p>This happens because in the line “SomeStruct struct2 = struct1;” the value of struct1 is <strong>copied </strong>to the struct2 variable. Later by changing struct1 we do not change struct2.<br>But assigning the <strong>class </strong>“SomeClass class2 = class1;” <strong>copies only reference</strong>. Now they both (class1 and class2) refer to the <strong>same place</strong> in the memory where instance of SomeClass is located. Thus, both of them reference the same instance, and its field is changed at the line “class1.x = 10”</p><h4>Passing as argument</h4><p>It works the same when passing it as an argument to some method</p><pre>void ClassExample2()<br>{<br>    Console.WriteLine(&quot;Classes&quot;);<br><br>    SomeClass class1 = new();<br>    class1.x = 5;<br>    ClassModify(class1);<br><br>    Console.WriteLine(class1.x);<br>}<br><br>void ClassModify(SomeClass inputClass)<br>{<br>    inputClass.x = 25;<br>}<br><br>void StructExample2()<br>{<br>    Console.WriteLine(&quot;Structs&quot;);<br><br>    SomeStruct struct1 = new();<br>    struct1.x = 5;<br>    StructModify(struct1);<br><br>    Console.WriteLine(struct1.x);<br>}<br><br>void StructModify(SomeStruct inputStruct)<br>{<br>    inputStruct.x = 25;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*4MJXJZqei7utJMXYgjfGqA.png" /></figure><p>But we can pass <strong>struct as a reference</strong> too. For that we’ll need to use keyword <strong>ref </strong>(or <strong>in/out</strong>)</p><pre>void StructExample2()<br>{<br>    Console.WriteLine(&quot;Structs&quot;);<br><br>    SomeStruct struct1 = new();<br>    struct1.x = 5;<br>    StructModify(ref struct1);<br><br>    Console.WriteLine(struct1.x);<br>}<br><br>void StructModify(ref SomeStruct inputStruct)<br>{<br>    inputStruct.x = 25;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*yfP4kC_UihP0gndTTNZSRA.png" /></figure><h4>Allocation</h4><p>Creating something in the Stack has a <strong>minimal </strong>performance impact.</p><p>Creating objects on the Heap incurs <strong>some</strong> small performance effects because of <strong>allocation</strong>, but the more significant impact on performance arises when these heap-allocated objects participate in the <strong>Garbage Collection</strong> cycle.</p><p><strong>Garbage collection</strong> is a broad topic, and it is important to understand how it works in order to write performant code. <br>You can learn about it here <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals">https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals</a></p><p><strong><em>Learn more about allocations</em></strong><em><br>Avoiding allocations </em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/"><em>https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/</em></a></p><h3>Common mistakes</h3><h4>Collections of mutable structs</h4><p>Modifying fields of non-readonly structs stored inside collections will result in <strong>compilation error</strong>. <br>You can still do it by creating a <strong>new struct</strong> and assigning it into the collection, but consider using a class if you need to do that often.</p><pre>List&lt;SomeClass&gt; classList = new List&lt;SomeClass&gt;();<br>List&lt;SomeStruct&gt; structList = new List&lt;SomeStruct&gt;();<br><br>...<br><br>classList[5].x = 5;     //ok<br>structList[5].x = 5;    //compilation error<br>structList[5] = new SomeStruct() { x = 25 };  //ok</pre><h4>Arrays of structs vs Arrays of classes</h4><p>If you create an array of structs, it allocates memory for the <strong>whole array</strong> and fills it with empty structs.<br>But if you create an array of classes it allocates memory <strong>only for references.</strong> The actual objects (instances of the class) will be allocated in the Heap <strong>separately </strong>from the array when you create them.</p><pre>//classes<br>SomeClass[] classArray = new SomeClass[1000];<br>classArray[15].x = 55;  //runtime error, NullReferenceException<br>Console.WriteLine(classArray[15].x);<br><br>//structs<br>SomeStruct[] structArray = new SomeStruct[1000];<br>structArray[15].x = 55; //ok<br>Console.WriteLine(structArray[15].x);</pre><p>Fixing NullReferenceException by creating class instances:</p><pre>for (int i = 0; i &lt; 1000; i++)<br>    classArray[i] = new SomeClass();</pre><h4>Boxing</h4><p>Structs allow us to achieve better performance. But there are some hidden traps that can affect their performance. One of the biggest is “<strong>boxing</strong>”’.</p><p><strong>Boxing </strong>is a process of wrapping a Value type and moving it to the Heap, producing an <strong>allocation</strong>. <br>Boxing happens when a Value type is <strong>casted </strong>to an (object) or interface. <br>Generally, you should <strong>avoid boxing</strong> for performance reasons.</p><p>Example case of boxing is:</p><pre>SomeStruct struct1 = new();<br>object structObj = struct1;  //boxing</pre><p><strong><em>More about boxing:<br></em></strong><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing"><em>https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing</em></a></p><h4>Inheritance</h4><p>Structs can inherit interfaces, but casting them to those interfaces will produce <strong>boxing, </strong>which should be avoided when possible</p><pre>SomeStructWithInheritance struct1 = new();<br>IDisposable structDisposable = struct1;  //boxing<br><br>List&lt;IDisposable&gt; disposables = new();<br>disposables.Add(struct1);   //boxing<br><br>public struct SomeStructWithInheritance : IDisposable<br>{<br>    public int x;<br><br>    public void Dispose()<br>    {<br>        //some code<br>    }<br>}</pre><h4>Lambdas</h4><p><strong>Lambdas capture</strong> Value types by using closure, it’s important to remember that because it may lead to unexpected behaviour</p><pre>int x = 5;<br>Action lambda = () =&gt; Console.WriteLine(x);<br>x = 10;<br>lambda();   //output in the console: 10</pre><p>If you want to pass only a copy of the value, you can do it like that:</p><pre>int x = 5;<br>int y = x;<br>Action lambda = () =&gt; Console.WriteLine(y);<br>x = 10;<br>lambda();   //output in the console: 5</pre><p><strong><em>You can read more about lambdas here:</em></strong><em><br></em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions"><em>https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions</em></a></p><h3>Advices</h3><h4>Make readonly structs</h4><p>To avoid mistakes when working with structs, mark your structs as readonly</p><pre>SomeStruct struct1 = new(5);<br>struct1.x = 25;  //compilation error<br><br>public readonly struct SomeStruct<br>{<br>    public readonly int x;<br><br>    public SomeStruct(int x)<br>    {<br>        this.x = x;<br>    }<br>}</pre><h4>Pass structs by reference for optimization</h4><p>Use the ref/in/out keyword to pass structs as references. It will increase <strong>performance</strong>, especially with big-sized structs</p><pre>void StructPrint(in SomeStruct inputStruct)<br>{<br>    Console.WriteLine(inputStruct.x);<br>}</pre><p><strong>Advanced<br></strong>If you use <strong>Array </strong>of structs, you can also modify its elements by accessing them as <strong>ref:</strong></p><pre>SomeStruct[] structs = new SomeStruct[1000000];<br><br>ModifySimple(); //slower<br>ModifyAsRefs(); //faster<br><br>//slower, with copying<br>void ModifySimple()<br>{<br>    for (int i = 0; i &lt; structs.Length; i++)<br>    {<br>        //modify struct itself, produces copying<br>        structs[i].x = 50;<br>    }<br>}<br><br>//faster, by ref<br>void ModifyAsRefs()<br>{<br>    for (int i = 0; i &lt; structs.Length; i++)<br>    {<br>        //take struct as reference<br>        ref SomeStruct structRef = ref structs[i];<br>        //modify reference<br>        structRef.x = 100;<br>    }<br>}<br><br>struct SomeStruct<br>{<br>    public int x;<br>    public int y;<br>    public int z;<br>    public int w;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaIjc4Fkl8v2VNUy_XFQXA.png" /><figcaption>Profiler</figcaption></figure><p>In this scenario it gives more than 2x performance boost<br><em>Thanks for this example to </em><a href="https://www.reddit.com/r/Unity3D/comments/17mwgiw/comment/k7onl19/?utm_source=share&amp;utm_medium=web2x&amp;context=3"><em>feralferrous</em></a></p><p>That works only with Arrays, any Collections wouldn’t allow that.<strong><em><br>What’s the difference between List and Array of structs?</em></strong><em><br></em><a href="https://levelup.gitconnected.com/modifying-struct-in-list-vs-array-6b4035b139b9"><em>https://levelup.gitconnected.com/modifying-struct-in-list-vs-array-6b4035b139b9</em></a></p><h4>Consider “ref structs” when that struct doesn’t leave the Stack</h4><p>If your struct should <strong>never leave the Stack</strong>, you can use “ref struct”, which would add extra <strong>restrictions </strong>on it and reduce the chance of making mistakes</p><pre>List&lt;SomeStruct&gt; list = new();  //compilation error because List is on the Heap<br><br>public readonly ref struct SomeStruct<br>{<br>    public readonly int x;<br><br>    public SomeStruct(int x)<br>    {<br>        this.x = x;<br>    }<br>}</pre><p><strong><em>You can learn more about ref struct and its restrictions here:</em></strong><em><br></em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct"><em>https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct</em></a></p><p><strong>Check out my other tutorial about structs:</strong><br>Optimizing Code by Replacing Classes with Structs, Unity C# Tutorial<br><a href="https://medium.com/@swiftroll3d/optimizing-code-by-replacing-classes-with-structs-unity-c-tutorial-f1dd3a0baf50">https://medium.com/@swiftroll3d/optimizing-code-by-replacing-classes-with-structs-unity-c-tutorial-f1dd3a0baf50</a></p><p>Consider following me for more tutorials here or at twitter <a href="https://twitter.com/SwiftRollDev">https://twitter.com/</a>SwiftRollDev</p><h3><em>More info</em></h3><p>The C# type system <a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/">https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/</a><br>Structure types <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct</a><br>Value types <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types</a><br>The Truth About Value Types (blog) <a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-truth-about-value-types">https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-truth-about-value-types</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c23043fce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Code by Replacing Classes with Structs, Unity C# Tutorial]]></title>
            <link>https://medium.com/@swiftroll3d/optimizing-code-by-replacing-classes-with-structs-unity-c-tutorial-f1dd3a0baf50?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1dd3a0baf50</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 13:04:35 GMT</pubDate>
            <atom:updated>2024-05-26T16:33:17.756Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>If you don’t find yourself understanding the </em><strong><em>difference between structs and classes</em></strong><em>, I would recommend researching that first. <br>Otherwise, it’s possible to do more harm than good, because they work very </em><strong><em>differently</em></strong><em>.<br>Here’s a link about structs at Microsoft documentation<br></em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct"><em>https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct</em></a></blockquote><p>This tutorial is intentionally short, focusing on practical implementation rather than theory.<br>However, I encourage you to go deeper into these topics for more efficient code without much of additional work.</p><h3>Allocation</h3><p>Let’s begin with simple code that demonstrates performance comparison between creating classes and structs.<br>We’ll create 1 million of each:</p><pre>public sealed class Example: MonoBehaviour<br>{<br>    private ClassData[] _classArray;<br>    private StructData[] _structArray;<br><br>    private void Start()<br>    {<br>        Profiler.BeginSample(&quot;Class creation&quot;);    //for performance measurements<br>        _classArray = new ClassData[1000000];<br>        for (int i = 0; i &lt; _classArray.Length; i++)<br>            _classArray[i] = new ClassData();<br>        Profiler.EndSample();  //for performance measurements<br><br>        Profiler.BeginSample(&quot;Struct creation&quot;);    //for performance measurements<br>        _structArray = new StructData[1000000];<br>        for (int i = 0; i &lt; _structArray.Length; i++)<br>            _structArray[i] = new StructData();<br>        Profiler.EndSample();  //for performance measurements<br>    }<br><br>    private sealed class ClassData<br>    {<br>        public int Value { get; }<br>    }<br><br>    private readonly struct StructData<br>    {<br>        public int Value { get; }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NUuRvuz9irmP8wuovSM6A.png" /><figcaption>Unity editor profiler screenshot</figcaption></figure><p>Let’s compare:<br><strong>Class</strong><br>- 26.7mb allocation<br>- 40.58ms<br><strong>Struct</strong><br>- 3.8mb allocation (~7x less)<br>- 1.88ms (~21x faster)</p><p>These numbers will vary for different types of data, but we can clearly see that structs perform better here.</p><p><strong><em>Why?</em></strong><em><br>Each new instance of class requires </em><strong><em>allocation </em></strong><em>inside managed memory, which has some performance cost.<br>Also any </em><strong><em>class instances require more memory</em></strong><em> than structs and have to be aligned inside managed memory.</em></p><p>Additionally, it’s important to remember that each class instance is <strong>individually allocated</strong> within the heap and participates in the <strong>Garbage Collection</strong> cycle. This effect on performance doesn’t end at allocation, it will affect GC collection later. And <strong>this </strong>is actually even more important reason to consider structs.</p><h3>Usage</h3><h4>Iterating</h4><p>Let’s add code that iterates through all the created objects</p><pre>private void Update()<br>{<br>    Profiler.BeginSample(&quot;Iterate Classes&quot;);    //for performance measurements<br>    IterateClasses();<br>    Profiler.EndSample();  //for performance measurements<br><br>    Profiler.BeginSample(&quot;Iterate Structs&quot;);    //for performance measurements<br>    IterateStructs();<br>    Profiler.EndSample();  //for performance measurements<br>}<br><br>private void IterateClasses()<br>{<br>    int sum = 0;<br>    for (int i = 0; i &lt; _classArray.Length; i++)<br>        sum += _classArray[i].Value;<br>}<br><br>private void IterateStructs()<br>{<br>    int sum = 0;<br>    for (int i = 0; i &lt; _structArray.Length; i++)<br>        sum += _structArray[i].Value;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4zQJWSGXA7htuneE3IRew.png" /></figure><p><strong>Classes</strong><br>- 6.58ms<br><strong>Structs</strong><br>- 4.28ms (~1.5x faster)</p><p><strong><em>Why?</em></strong><em><br>“</em><strong><em>Data locality</em></strong><em>” of elements inside the array. <br>If it’s an </em><strong><em>array (or collection) of structs</em></strong><em>, then the data in memory is </em><strong><em>located directly</em></strong><em> inside the array and goes sequentially, and that increases “</em><strong><em>cache hits</em></strong><em>”. <br>Opposite to that, </em><strong><em>array (or collection) of classes contains only references</em></strong><em> for instances and these instances may be scattered randomly in memory so the </em><strong><em>performance will vary</em></strong><em> from case to case.<br>Also there’s underlying </em><strong><em>dereferencing </em></strong><em>to access class instances.</em></p><h4>Passing</h4><p>There’s 3 ways we can pass these values to methods:</p><ul><li>Class</li><li>Struct</li><li>Struct by reference (ref/in/out keywords)</li></ul><p>We’ll try all of them and measure:</p><pre>private int _sum;<br><br>private void Update()<br>{<br>    ClassData classData = new();<br>    StructData structData = new();<br><br>    Profiler.BeginSample(&quot;Pass class&quot;);<br>    for (int i = 0; i &lt; 1000000; i++)<br>        PassClass(classData);<br>    Profiler.EndSample();<br><br>    Profiler.BeginSample(&quot;Pass struct&quot;);<br>    for (int i = 0; i &lt; 1000000; i++)<br>        PassStruct(structData);<br>    Profiler.EndSample();<br><br>    Profiler.BeginSample(&quot;Pass struct by ref&quot;);<br>    for (int i = 0; i &lt; 1000000; i++)<br>        PassStructByRef(in structData);<br>    Profiler.EndSample();<br>}<br><br>private void PassClass(ClassData data) =&gt; _sum += data.Value;<br>private void PassStruct(StructData data) =&gt; _sum += data.Value;<br>private void PassStructByRef(in StructData data) =&gt; _sum += data.Value;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLUvZazBzZb6zksVvzyMtQ.png" /></figure><p>Passing struct by reference is fastest in this scenario.</p><p>Now let’s modify the data to take more memory:</p><pre>private sealed class ClassData<br>{<br>    public int Value { get; }<br>    public int Value1 { get; }<br>    public int Value2 { get; }<br>    public int Value3 { get; }<br>    public int Value4 { get; }<br>}<br><br>private readonly struct StructData<br>{<br>    public int Value { get; }<br>    public int Value1 { get; }<br>    public int Value2 { get; }<br>    public int Value3 { get; }<br>    public int Value4 { get; }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aw1sSsk6abLq1gmz-zEY-w.png" /></figure><p>Passing directly by structs becomes heaviest because more data means more time to <strong>copy</strong> it.<br>But passing <strong>struct by reference</strong> still has <strong>best performance</strong>.</p><p>Consider passing a <strong>struct by reference when it’s possible</strong>, especially if it’s not very small struct memory-wise.</p><h3>Advices</h3><ul><li>Most likely you won’t need mutable structs, prefer using <strong>readonly</strong> structs unless you know what you’re doing</li><li>Consider using structs in <strong>performance-heavy</strong> parts of your code and when there’s long<strong> collections</strong> of not too heavy data</li><li>Don’t make <strong>too heavy structs</strong>. If the objects takes a lot of memory, then it’s usually better to make it a class, otherwise <strong>copying</strong> will decrease performance</li><li>When working with structs, <strong>avoid “boxing.”</strong> If you find the need to “box” something, consider using a class instead.</li></ul><p>Also check out my tutorial about <strong>Avoiding Mistakes When Using Structs in C#<br></strong><a href="https://medium.com/@swiftroll3d/avoiding-mistakes-when-using-structs-in-c-b1c23043fce0">https://medium.com/@swiftroll3d/avoiding-mistakes-when-using-structs-in-c-b1c23043fce0</a></p><p><strong><em>What I used for measurement</em></strong><em><br>Laptop with AMD Ryzen 9 5900HX CPU</em></p><blockquote><strong><em>Additional materials<br></em></strong><em>- Microsoft guide to decide between class and struct </em><a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct"><em>https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct</em></a><em> <br>- Microsoft docs optimisation 1 </em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/"><em>https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/</em></a><em> <br>- Microsoft docs optimisation 2 </em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/ref-tutorial"><em>https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/ref-tutorial</em></a><em><br>- Book “Pro .NET Memory Management” </em><a href="https://prodotnetmemory.com/"><em>https://prodotnetmemory.com/</em></a></blockquote><p>Consider following me for more tutorials here or at twitter <a href="https://twitter.com/SwiftRollDev">https://twitter.com/SwiftRollDev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1dd3a0baf50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve performance of RaycastAll by using RaycastNonAlloc in Unity]]></title>
            <link>https://medium.com/@swiftroll3d/how-to-improve-performance-of-raycastall-by-using-raycastnonalloc-in-unity-ab9409064ff4?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9409064ff4</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[raycasting]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 07:01:49 GMT</pubDate>
            <atom:updated>2023-10-30T07:03:21.673Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need to use RaycastAll often (like each frame of your game), consider switching to RaycastNonAlloc method which acts faster and doesn’t produce memory allocations (so it doesn’t put extra load on Garbage Collector)</p><pre>public sealed class RaycastExample : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        Profiler.BeginSample(&quot;Bad&quot;);    //for performance measurements<br>        //do 1000 raycasts<br>        for (int i = 0; i &lt; 1000; i++)<br>            RaycastBad();<br>        Profiler.EndSample();<br><br>        Profiler.BeginSample(&quot;Good&quot;);    //for performance measurements<br>        //do 1000 raycasts<br>        for (int i = 0; i &lt; 1000; i++)<br>            RaycastGood();<br>        Profiler.EndSample();<br>    }<br><br>    private void RaycastBad()<br>    {<br>        RaycastHit[] hits = Physics.RaycastAll(transform.position, transform.forward, 100.0f);<br>    }<br><br>    private readonly RaycastHit[] _hits = new RaycastHit[5];<br>    private void RaycastGood()<br>    {<br>        int hitsNum = Physics.RaycastNonAlloc(transform.position, transform.forward, _hits, 100.0f);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*RlBx8bivSRLFeRkceZRVHw.png" /><figcaption>Profiler screenshot</figcaption></figure><p>As you can see, it’s almost 2x faster and takes 0 bytes of memory</p><p>However, as you can see, now results of the raycast are limited to length of the array, so it’s important to choose the length of the array correctly so it could fit everything you might need while not taking much of excessive memory</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9409064ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity built-in pooling of collections (List/Dictionary/other)]]></title>
            <link>https://medium.com/@swiftroll3d/unity-built-in-pooling-of-collections-list-dictionary-other-536c6bf6859c?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/536c6bf6859c</guid>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[object-pool]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 00:00:48 GMT</pubDate>
            <atom:updated>2023-10-29T00:00:48.520Z</atom:updated>
            <content:encoded><![CDATA[<p>Any new() collection in C# creates allocation which increases load on Garbage Collector (in short, it costs you a little of your game’s performance)</p><p>You can avoid it by using Unity’s built-in ListPool/DictionaryPool/etc or even build your own pooling</p><p>Consider this for performance-heavy parts of the game, like things in Update()</p><pre>public sealed class ListPoolExample : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        Profiler.BeginSample(&quot;Bad&quot;);    //for performance measurements<br>        GetColliersBad();<br>        Profiler.EndSample();<br><br>        Profiler.BeginSample(&quot;Good&quot;);   //for performance measurements<br>        GetColliersGood();<br>        Profiler.EndSample();<br>    }<br><br>    //don&#39;t use this<br>    private void GetColliersBad()<br>    {<br>        //just get components without pooling<br>        GetComponents&lt;Collider&gt;();<br>    }<br><br>    //use this<br>    private void GetColliersGood()<br>    {<br>        //get list from pool<br>        List&lt;Collider&gt; colliders = ListPool&lt;Collider&gt;.Get();<br><br>        //get components to pooled list<br>        GetComponentsInChildren&lt;Collider&gt;(colliders);<br><br>        //return list to pool<br>        ListPool&lt;Collider&gt;.Release(colliders);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*GA_gUc7j5B_h4Z18" /><figcaption>Profiler screenshot</figcaption></figure><p>It’s also possible to use that for other types of collections and even just objects</p><p>If you’re interested in that, here’s another good article that talks about it in general:<br><a href="https://medium.com/waveaccess/new-pooling-api-in-unity-2021-3b88fb86a5d5">https://medium.com/waveaccess/new-pooling-api-in-unity-2021-3b88fb86a5d5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=536c6bf6859c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command Pattern Allocation Free in C# Unity / Godot (without memory allocations)]]></title>
            <link>https://medium.com/@swiftroll3d/command-pattern-allocation-free-in-c-unity-godot-without-memory-allocations-1b60cfcbd4e2?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b60cfcbd4e2</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[godot]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 15:02:00 GMT</pubDate>
            <atom:updated>2023-10-27T17:11:00.295Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>In short — What is this article about?<br></em></strong><em>How to use Command pattern in C# without producing heap allocations for each new command</em></p><p>Github link: <a href="https://github.com/swiftroll/CommandsWithoutAllocationsTutorial">https://github.com/swiftroll/CommandsWithoutAllocationsTutorial</a></p><h4><strong>Motivation</strong></h4><p>Command pattern is very useful pattern for many things, but in usual approach each new command instance produces heap allocation, because it’s an instance of the whole command class.</p><p>In most cases it’s ok and shouldn’t be a concern, but in some scenarios you may approach your game architecture in a way that heavily relies on commands usage and creates them really often, which makes performance impact visible.</p><p>In that case, it’s better to design whole commands system in a way that doesn’t require additional allocations for each command, and acts more in a Data-Oriented way.</p><p><strong><em>Why allocations are bad?<br></em></strong><em>While allocations are cheap, after each allocation there’s a chance of running garbage collection cycle, which usually takes decent time and can visibly affect performance. And more important — each allocated instance increases the time garbage collector needs to perform its cycle.</em></p><p><em>You can read more about it here: </em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/*"><em>https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/performance/</em></a></p><p><strong><em>Using pooling<br></em></strong><em>If your usage of commands isn’t too heavy or if you don’t need to store the history of commands (undo and redo), then it’s better to use simple solution of pooling commands.</em></p><h4><strong>Part 1 — Usual command pattern with heap allocations</strong></h4><p>Let’s start with usual command pattern implementation</p><pre>public interface ICommand<br>{<br>    void Execute();<br>    void Undo();<br>}<br><br>public sealed class CommandSpawnCube : ICommand<br>{<br>    private readonly string _name;<br>    private readonly Vector3 _position;<br>    private readonly Vector3 _scale;<br><br>    private GameObject _spawnedCube;<br><br>    public CommandSpawnCube(string name, Vector3 position, Vector3 scale)<br>    {<br>        _name = name;<br>        _position = position;<br>        _scale = scale;<br>    }<br><br>    public void Execute()<br>    {<br>        _spawnedCube = GameObject.CreatePrimitive(PrimitiveType.Cube);<br>        _spawnedCube.name = _name;<br>        _spawnedCube.transform.position = _position;<br>        _spawnedCube.transform.localScale = _scale;<br>    }<br><br>    public void Undo()<br>    {<br>        Object.Destroy(_spawnedCube);<br>    }<br>}<br><br>public sealed class CommandMoveObject : ICommand<br>{<br>    private readonly string _targetName;<br>    private readonly Vector3 _destination;<br><br>    private Vector3 _originalPosition;<br><br>    public CommandMoveObject(string targetName, Vector3 destination)<br>    {<br>        _targetName = targetName;<br>        _destination = destination;<br>    }<br><br>    public void Execute()<br>    {<br>        //in real projects don&#39;t use GameObject.Find, here it&#39;s used for simplicity<br>        //because if we would use reference to GameObject, it will become null in case of destruction (by Undo of CommandSpawnCube)<br>        var target = GameObject.Find(_targetName);<br><br>        _originalPosition = target.transform.position;<br>        target.transform.position = _destination;<br>    }<br><br>    public void Undo()<br>    {<br>        var target = GameObject.Find(_targetName);<br>        <br>        target.transform.position = _originalPosition;<br>    }<br>}</pre><p>Here’s is class that encapsulates working with commands:</p><pre>public sealed class CommandInvoker<br>{<br>    private readonly Stack&lt;ICommand&gt; _history = new();<br>    private readonly Stack&lt;ICommand&gt; _undoneCommands = new();<br><br>    public void Execute(ICommand cmd)<br>    {<br>        _undoneCommands.Clear();<br><br>        cmd.Execute();<br><br>        _history.Push(cmd);<br>    }<br><br>    public void Undo()<br>    {<br>        var cmd = _history.Pop();<br><br>        cmd.Undo();<br><br>        _undoneCommands.Push(cmd);<br>    }<br><br>    public void Redo()<br>    {<br>        if (_undoneCommands.TryPop(out var cmd))<br>        {<br>            cmd.Execute();<br><br>            _history.Push(cmd);<br>        }<br>    }<br>}</pre><p>And the code for testing them:</p><pre>public sealed class CommandsExample : MonoBehaviour<br>{<br>    private readonly CommandInvoker _invoker = new();<br><br>    private void Update()<br>    {<br>        if (Input.GetKeyDown(KeyCode.Q))<br>        {<br>            Execute();<br>        }<br>    }<br><br>    [ContextMenu(nameof(Execute))]<br>    public void Execute()<br>    {<br>        for (int i = 0; i &lt; 100; i++)<br>        {<br>            string name = $&quot;Cube_{i:000}&quot;;<br><br>            CommandSpawnCube commandSpawnCube = new(name, Vector3.zero, Vector3.one);<br>            _invoker.Execute(commandSpawnCube);<br><br>            CommandMoveObject commandMoveObject = new(name, new Vector3(2f, 1f, 4f));<br>            _invoker.Execute(commandMoveObject);<br>        }<br>    }<br><br>    [ContextMenu(nameof(Undo))]<br>    public void Undo()<br>    {<br>        _invoker.Undo();<br>    }<br><br>    [ContextMenu(nameof(Redo))]<br>    public void Redo()<br>    {<br>        _invoker.Redo();<br>    }<br>}</pre><p>Which gets us this in a profiler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGmvFAneQSPvA9qQlmCW-g.png" /><figcaption>Profiler</figcaption></figure><p>Here you can see 300 heap allocations, because each command execution creates new command to execute it, which increases the load on garbage collector</p><ul><li>100 of allocations are produced by string name = $&quot;Cube_{i:000}&quot;; - this is not connected to commands themselves and is ok to keep</li><li>100 by creating new instance of command CommandSpawnCube</li><li>100 by creating new instance of command CommandMoveObject</li></ul><p>So how can we fix this and use that many commands as we want and not get any allocations?</p><h4><strong>Part 2 — Allocation-free commands</strong></h4><p>For us to avoid allocations, we have to avoid creating new commands during gameplay and any possible additional allocations (like boxing)</p><p><strong><em>What is boxing?<br></em></strong><em>Boxing can happen in cases like when you cast value-type variable to its interface or to (object). Also using an operator IS or pattern-matching switch on value-type will produce allocation through boxing.</em></p><p><em>It is an interesting topic, you can read more about it here: </em><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing*"><em>https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing</em></a></p><p>To achieve this, we will create one instance of each command at the start and will reuse them.</p><p>For it to work as intended, we also have to remove all data fields from commands and send command data in a struct type as an argument in Execute(..) method.</p><pre>public interface ICommand&lt;T&gt; where T : struct<br>{<br>    void Execute(T args);<br>}<br><br>public sealed class CommandSpawnCube : ICommand&lt;CommandSpawnCubeArgs&gt;<br>{<br>    public void Execute(CommandSpawnCubeArgs args)<br>    {<br>        var spawnedCube = GameObject.CreatePrimitive(PrimitiveType.Cube);<br>        spawnedCube.name = args.Name;<br>        spawnedCube.transform.position = args.Position;<br>        spawnedCube.transform.localScale = args.Scale;<br>    }<br>}<br>public sealed class CommandMoveObject : ICommand&lt;CommandMoveObjectArgs&gt;<br>{<br>    public void Execute(CommandMoveObjectArgs args)<br>    {<br>        var target = GameObject.Find(args.TargetName);<br><br>        target.transform.position = args.Position;<br>    }<br>}<br><br><br>//structures with commands data:<br><br>public readonly struct CommandSpawnCubeArgs<br>{<br>    public readonly string Name;<br>    public readonly Vector3 Position;<br>    public readonly Vector3 Scale;<br><br>    public CommandSpawnCubeArgs(string name, Vector3 position, Vector3 scale)<br>    {<br>        Name = name;<br>        Position = position;<br>        Scale = scale;<br>    }<br>}<br><br>public readonly struct CommandMoveObjectArgs<br>{<br>    public readonly string TargetName;<br>    public readonly Vector3 Position;<br><br>    public CommandMoveObjectArgs(string targetName, Vector3 position)<br>    {<br>        TargetName = targetName;<br>        Position = position;<br>    }<br>}</pre><p>Then we will create a class which will provide access to commands execution to its users</p><pre>public sealed class CommandInvoker<br>{<br>    private readonly CommandSpawnCube _spawnCube = new();<br>    private readonly CommandMoveObject _movePosition = new();<br><br>    public void Execute&lt;T&gt;(CommandType commandType, T args) where T : struct<br>    {<br>        var cmd = GetCommand&lt;T&gt;(commandType);<br><br>        if (cmd == null)<br>        {<br>            throw new ArgumentException($&quot;Can&#39;t find command for type {commandType} and args {args.GetType().Name}&quot;);<br>        }<br><br>        cmd.Execute(args);<br>    }<br><br>    private ICommand&lt;T&gt; GetCommand&lt;T&gt;(CommandType commandType) where T : struct<br>    {<br>        ICommand&lt;T&gt; result;<br><br>        switch (commandType)<br>        {<br>            case CommandType.SpawnCube:<br>                result = _spawnCube as ICommand&lt;T&gt;;<br>                break;<br>            case CommandType.MoveObject:<br>                result = _movePosition as ICommand&lt;T&gt;;<br>                break;<br>            default: throw new ArgumentException($&quot;Invalid command type {commandType}&quot;);<br>        }<br><br>    return result;<br>    }<br>}<br><br>public enum CommandType<br>{<br>    SpawnCube,<br>    MoveObject,<br>}</pre><p>Let’s try to run this</p><pre>public sealed class CommandsExample : MonoBehaviour<br>{<br>    private readonly CommandInvoker _invoker = new();<br><br>    private void Update()<br>    {<br>        if (Input.GetKeyDown(KeyCode.Q))<br>        {<br>            Execute();<br>        }<br>    }<br><br>    [ContextMenu(nameof(Execute))]<br>    public void Execute()<br>    {<br>        for (int i = 0; i&lt; 100; i++)<br>        {<br>            string name = $&quot;Cube_{i:000}&quot;;<br><br>            _invoker.Execute(CommandType.SpawnCube, new CommandSpawnCubeArgs(name, Vector3.zero, Vector3.one));<br>            _invoker.Execute(CommandType.MoveObject, new CommandMoveObjectArgs(name, new Vector3(2f, 1f, 4f)));<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkTK_B1GDERG9iHk3IdZZQ.png" /><figcaption>Profiler</figcaption></figure><p>We get no allocations (except for Mono.JIT, but it’s compilation allocations and are ok), but our commands don’t have undo and redo functionality and don’t even inherit common interface, now they’re kind of useless because the whole point of them is broken.</p><p>Let’s fix that</p><h4><strong>Part 3 — Restoring Undo functionality</strong></h4><p>Let’s start with Undo logic</p><p>We’ll add Undo logics to our existing commands</p><pre>public interface ICommand&lt;T&gt; where T : struct<br>{<br>    void Execute(T args);<br>    void Undo();<br>}<br><br>public sealed class CommandSpawnCube : ICommand&lt;CommandSpawnCubeArgs&gt;<br>{<br>    public void Execute(CommandSpawnCubeArgs args)<br>    {<br>        var spawnedCube = GameObject.CreatePrimitive(PrimitiveType.Cube);<br>        spawnedCube.name = args.Name;<br>        spawnedCube.transform.position = args.Position;<br>        spawnedCube.transform.localScale = args.Scale;<br>    }<br><br>    public void Undo()<br>    {<br>        //todo destroy cube somehow<br>    }<br>}<br>public sealed class CommandMoveObject : ICommand&lt;CommandMoveObjectArgs&gt;<br>{<br>    public void Execute(CommandMoveObjectArgs args)<br>    {<br>        var target = GameObject.Find(args.TargetName);<br><br>        target.transform.position = args.Position;<br>    }<br><br>    public void Undo()<br>    {<br>        //todo move obj back somehow<br>    }<br>}</pre><p>But as we see they can’t work without their data, which should be collected during their Execute method.</p><p>CommandSpawnCube has to know which object was created to destroy it in Undo(), and CommandMoveObject has to know what object to move and what was its previous position.</p><p>In original Command pattern this data would be stored in fields of the command, but we don’t have such luxury because we use only 1 instance of each command class, so we’ll add external storage of that kind of data.</p><p>Let’s make it that our Execute commands collect the data needed for Undo, and return it to the caller.</p><p>Each command have different set of data required for that, so we’ll add additional struct for each command</p><pre>public interface ICommand&lt;T0, T1&gt;<br>    where T0 : struct<br>    where T1 : struct<br>{<br>    T1 Execute(T0 args);<br>    void Undo(T1 args);<br>}</pre><pre>public readonly struct CommandSpawnCubeUndoArgs<br>{<br>    public readonly GameObject Cube;<br><br>    public CommandSpawnCubeUndoArgs(GameObject cube)<br>    {<br>        Cube = cube;<br>    }<br>}<br><br>public readonly struct CommandMoveObjectUndoArgs<br>{<br>    public readonly string TargetName;<br>    public readonly Vector3 OriginalPosition;<br><br>    public CommandMoveObjectUndoArgs(string targetName, Vector3 originalPosition)<br>    {<br>        TargetName = targetName;<br>        OriginalPosition = originalPosition;<br>    }<br>}</pre><pre>public sealed class CommandSpawnCube : ICommand&lt;CommandSpawnCubeArgs, CommandSpawnCubeUndoArgs&gt;<br>{<br>    public CommandSpawnCubeUndoArgs Execute(CommandSpawnCubeArgs args)<br>    {<br>        var spawnedCube = GameObject.CreatePrimitive(PrimitiveType.Cube);<br>        spawnedCube.name = args.Name;<br>        spawnedCube.transform.position = args.Position;<br>        spawnedCube.transform.localScale = args.Scale;<br><br>        return new CommandSpawnCubeUndoArgs(spawnedCube);<br>    }<br><br>    public void Undo(CommandSpawnCubeUndoArgs args)<br>    {<br>        Object.Destroy(args.Cube);<br>    }<br>}<br>public sealed class CommandMoveObject : ICommand&lt;CommandMoveObjectArgs, CommandMoveObjectUndoArgs&gt;<br>{<br>    public CommandMoveObjectUndoArgs Execute(CommandMoveObjectArgs args)<br>    {<br>        var target = GameObject.Find(args.TargetName);<br><br>        var originalPosition = target.transform.position;<br>        target.transform.position = args.Position;<br><br>        return new CommandMoveObjectUndoArgs(args.TargetName, originalPosition);<br>    }<br><br>    public void Undo(CommandMoveObjectUndoArgs args)<br>    {<br>        var target = GameObject.Find(args.TargetName);<br><br>        target.transform.position = args.OriginalPosition;<br>    }<br>}</pre><p>Now our Execute method returns Undo arguments, which can be used to call Undo method.</p><p>Our commands classes are now ready to support Undo feature, so it’s time to design the ability of the commands invoker to use that</p><p>Main difficulty about that is deciding how to store Undo arguments for history.</p><p>Simplest approach that comes to mind is storing all Undo arguments in one collection, like Stack, which would allow us to just Pop() last argument and use to call Undo method.</p><p>But we use separate structs for each commands type, which forbids us from referring to them by any common interface (actually we can do that, but it will add boxing allocations, and that breaks the whole point of this)</p><p>So we have to store each Undo argument struct in separate collection.</p><p>Kind of like that:</p><pre>//this code is just for illustrating the idea<br><br>private readonly Stack&lt;CommandSpawnCubeUndoArgs&gt; _undoArgsSpawnCube;<br>private readonly Stack&lt;CommandMoveObjectUndoArgs&gt; _undoArgsMoveObj;</pre><p>That type of storage will allow us to work with that, but it doesn’t store order in which commands were executed</p><p>Most simple way to use this kind of storage with the right order would be like that:</p><pre>//this code is just for illustrating the idea<br><br>//storing order in which commands were executed<br>private readonly Stack&lt;CommandType&gt; _undoCommandTypes;<br><br>..<br><br>public enum CommandType<br>{<br>    SpawnCube,<br>    MoveObject,<br>}<br><br>..<br><br>public void Undo()<br>{<br>    var commandType = _undoCommandTypes.Pop();  //pop CommandType from history stack<br><br>    //decide which command to undo based on CommandType<br>    switch (commandType)<br>    {<br>        case CommandType.SpawnCube:<br>            _spawnCube.Undo(_undoArgsSpawnCube.Pop());   //undo SpawnCube command<br>            break;<br>        case CommandType.MoveObject:<br>            _movePosition.Undo(_undoArgsMoveObj.Pop());  //undo MoveObject command<br>            break;<br>    }<br>}</pre><p>And it will work, it’s not bad code</p><p>But it will require to add new switch cases to this Undo when each new command is introduced, and also adding new stack for storage, adding new lines for storing that after execution, and all that.</p><p>And we can avoid doing all that manual work by some changes in the design.</p><h4><strong>Other approach</strong></h4><p>There’s a better option — we can create ICommandWrapper and store history stack inside it.</p><p>We’ll also add Redo stack inside there too, it works similar.</p><pre>public interface ICommandWrapper<br>{<br>    void Undo();<br>    void Redo();<br>  void ClearRedo();<br>}<br><br>public sealed class CommandWrapper&lt;T0, T1&gt; : ICommandWrapper<br>  where T0 : struct //exec args<br>  where T1 : struct //undo args<br>{<br>    public CommandType CommandType { get; private set; }<br><br>    private readonly ICommand&lt;T0, T1&gt; _cmd;<br><br>    private readonly Stack&lt;HistoryEntry&gt; _history = new();<br>    private readonly Stack&lt;T0&gt; _toRedo = new();<br><br>    public CommandWrapper(ICommand&lt;T0, T1&gt; cmd, CommandType commandType)<br>    {<br>        _cmd = cmd;<br>        CommandType = commandType;<br>    }<br><br>    public void Execute(T0 args)<br>    {<br>        ClearRedo();<br>        _history.Push(new(args, _cmd.Execute(args)));<br>    }<br><br>    public void Undo()<br>    {<br>        var undoArgs = _history.Pop();<br><br>        _cmd.Undo(undoArgs.UndoArgs);<br>        _toRedo.Push(undoArgs.ExecutionArgs);<br>    }<br><br>    public void Redo()<br>    {<br>        var args = _toRedo.Pop();<br>        _history.Push(new(args, _cmd.Execute(args)));<br>    }<br><br>    public void ClearRedo()<br>    {<br>        _toRedo.Clear();<br>    }<br><br>    private readonly struct HistoryEntry<br>    {<br>        public readonly T0 ExecutionArgs;<br>        public readonly T1 UndoArgs;<br><br>        public HistoryEntry(T0 executionArgs, T1 undoArgs)<br>        {<br>            ExecutionArgs = executionArgs;<br>            UndoArgs = undoArgs;<br>        }<br>    }<br>}</pre><p>Then, in CommandInvoker add Undo and Redo methods which use dictionary to decide which wrapper to use.</p><pre>public sealed class CommandInvoker<br>{<br>    //all wrappers by CommandType<br>    private Dictionary&lt;CommandType, ICommandWrapper&gt; _commandWrappers = new();<br><br>    //wrappers<br>    private readonly CommandWrapper&lt;CommandSpawnCubeArgs, CommandSpawnCubeUndoArgs&gt; _spawnCube;<br>    private readonly CommandWrapper&lt;CommandMoveObjectArgs, CommandMoveObjectUndoArgs&gt; _moveObject;<br><br>    //undo and redo<br>    private readonly Stack&lt;CommandType&gt; _undoCommandTypes = new();<br>    private readonly Stack&lt;CommandType&gt; _redoCommandTypes = new();<br><br>    public CommandInvoker()<br>    {<br>        //create wrappers<br>        _spawnCube = new(new CommandSpawnCube(), CommandType.SpawnCube);<br>        _moveObject = new(new CommandMoveObject(), CommandType.MoveObject);<br><br>        //add them to dictionary<br>        _commandWrappers.Add(CommandType.SpawnCube, _spawnCube);<br>        _commandWrappers.Add(CommandType.MoveObject, _moveObject);<br>    }<br><br>    public void ExecuteSpawnCube(CommandSpawnCubeArgs args)<br>    {<br>        _spawnCube.Execute(args);    //ask wrapper to execute<br>        _undoCommandTypes.Push(CommandType.SpawnCube);  //add command type to history stack<br>        ClearRedo();<br>    }<br><br>    public void ExecuteMoveObject(CommandMoveObjectArgs args)<br>    {<br>        _moveObject.Execute(args);<br>        _undoCommandTypes.Push(CommandType.MoveObject);<br>        ClearRedo();<br>    }<br><br>    public void Undo()<br>    {<br>        var commandType = _undoCommandTypes.Pop();  //pop command type from history stack<br><br>        _commandWrappers[commandType].Undo();   //ask wrapper of this command type to undo<br>        <br>        _redoCommandTypes.Push(commandType);    //push command in redo stack<br>    }<br><br>    public void Redo()<br>    {<br>        var commandType = _redoCommandTypes.Pop();<br><br>        _commandWrappers[commandType].Redo();<br><br>        _undoCommandTypes.Push(commandType);<br>    }<br><br>    private void ClearRedo()<br>    {<br>        _redoCommandTypes.Clear();<br>        _spawnCube.ClearRedo();<br>        _moveObject.ClearRedo();<br>    }<br>}</pre><p>Let’s see how it works</p><pre>public sealed class CommandsExample : MonoBehaviour<br>{<br>    private readonly CommandInvoker _invoker = new();<br><br>    private void Update()<br>    {<br>        if (Input.GetKeyDown(KeyCode.Q))<br>        {<br>            Execute();<br>        }<br>    }<br><br>    [ContextMenu(nameof(Execute))]<br>    public void Execute()<br>    {<br>        for (int i = 0; i&lt; 100; i++)<br>        {<br>            string name = $&quot;Cube_{i:000}&quot;;<br><br>            _invoker.ExecuteSpawnCube(new CommandSpawnCubeArgs(name, Vector3.zero, Vector3.one));<br>            _invoker.ExecuteMoveObject(new CommandMoveObjectArgs(name, new Vector3(2f, 1f, 4f)));<br>        }<br>    }<br><br>    [ContextMenu(nameof(Undo))]<br>    public void Undo()<br>    {<br>        _invoker.Undo();<br>    }<br><br>    [ContextMenu(nameof(Redo))]<br>    public void Redo()<br>    {<br>        _invoker.Redo();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0e5JxGhwOSbU7HWxK5_lww.png" /><figcaption>Profiler</figcaption></figure><p>100 allocations that are left are caused by string name = $”Cube_{i:000}”; which is ok and is not connected to commands themselves</p><h4><strong>Part 4 — Limit the history</strong></h4><p>Now your history stack is limitless, so if you have thousands of commands being called regularly, it will just keep bloating user’s memory. To limit history, we would need to erase oldest elements in history. And because it’s a stack, we cannot access those elements, because they’re at stack’s beginning.</p><p>We need some data structure that allows us to get elements from both ends.</p><p>Perfect data structure for that would be <strong>Double-Ended Queue (or Deque)</strong>, but C# doesn’t have that built-in.</p><p>Closest relative to it would be <strong>LinkedList</strong>, but it produces allocation on each insertion, and we can’t afford that.</p><p>So the most efficient approach would be to implement your own Deque or some alternative to that.</p><p>I will not implement it here because it’s a topic for separate article, but you can google how to do that or just improvise.</p><h4><strong>Alternative</strong></h4><p>I will stick to not so good, but fast and easy way to get what we want without deque or things like that, so here’s the version with Stacks changed to <strong>Lists</strong></p><pre>public interface ICommandWrapper<br>{<br>    void Undo();<br>    void Redo();<br>    void ClearRedo();<br>    void EraseOldestHistoryEntry(); //new<br>}<br><br>public sealed class CommandWrapper&lt;T0, T1&gt; : ICommandWrapper<br>    where T0 : struct //exec args<br>    where T1 : struct //undo args<br>{<br>    public CommandType CommandType { get; private set; }<br><br>    private readonly ICommand&lt;T0, T1&gt; _cmd;<br><br>    private readonly List&lt;HistoryEntry&gt; _history = new();<br>    private readonly Stack&lt;T0&gt; _toRedo = new();<br><br>    public CommandWrapper(ICommand&lt;T0, T1&gt; cmd, CommandType commandType)<br>    {<br>        _cmd = cmd;<br>        CommandType = commandType;<br>    }<br><br>    public void Execute(T0 args)<br>    {<br>        ClearRedo();<br>        _history.Add(new(args, _cmd.Execute(args)));<br>    }<br><br>    public void Undo()<br>    {<br>        //new <br>        var undoArgs = _history[_history.Count - 1];<br>        _history.RemoveAt(_history.Count - 1);  //remove after taking<br>        // <br><br>        _cmd.Undo(undoArgs.UndoArgs);<br>        _toRedo.Push(undoArgs.ExecutionArgs);<br>    }<br><br>    public void Redo()<br>    {<br>        var args = _toRedo.Pop();<br>        _history.Add(new(args, _cmd.Execute(args)));<br>    }<br><br>    public void ClearRedo()<br>    {<br>        _toRedo.Clear();<br>    }<br><br>    //new <br>    public void EraseOldestHistoryEntry()<br>    {<br>        _history.RemoveAt(0);<br>    }<br><br>    private readonly struct HistoryEntry<br>    {<br>        public readonly T0 ExecutionArgs;<br>        public readonly T1 UndoArgs;<br><br>        public HistoryEntry(T0 executionArgs, T1 undoArgs)<br>        {<br>            ExecutionArgs = executionArgs;<br>            UndoArgs = undoArgs;<br>        }<br>    }<br>}</pre><pre>public sealed class CommandInvoker<br>{<br>    //all wrappers by CommandType<br>    private Dictionary&lt;CommandType, ICommandWrapper&gt; _commandWrappers = new();<br><br>    //wrappers<br>    private readonly CommandWrapper&lt;CommandSpawnCubeArgs, CommandSpawnCubeUndoArgs&gt; _spawnCube;<br>    private readonly CommandWrapper&lt;CommandMoveObjectArgs, CommandMoveObjectUndoArgs&gt; _moveObject;<br><br>    //undo and redo<br>    private readonly List&lt;CommandType&gt; _undoCommandTypes = new(_maxUndoCount); //new <br>    private readonly Stack&lt;CommandType&gt; _redoCommandTypes = new();<br><br>    private const int _maxUndoCount = 4;    //undo memory limit //new <br><br>    public CommandInvoker()<br>    {<br>        //create wrappers<br>        _spawnCube = new(new CommandSpawnCube(), CommandType.SpawnCube);<br>        _moveObject = new(new CommandMoveObject(), CommandType.MoveObject);<br><br>        //add them to dictionary<br>        _commandWrappers.Add(CommandType.SpawnCube, _spawnCube);<br>        _commandWrappers.Add(CommandType.MoveObject, _moveObject);<br>    }<br><br>    public void ExecuteSpawnCube(CommandSpawnCubeArgs args)<br>    {<br>        _spawnCube.Execute(args);    //ask wrapper to execute<br>        AddToUndo(CommandType.SpawnCube);  //add command type to history stack<br>        ClearRedo();<br>    }<br><br>    public void ExecuteMoveObject(CommandMoveObjectArgs args)<br>    {<br>        _moveObject.Execute(args);<br>        AddToUndo(CommandType.MoveObject);<br>        ClearRedo();<br>    }<br><br>    public void Undo()<br>    {<br>        //new <br>        var commandType = _undoCommandTypes[_undoCommandTypes.Count - 1];  //pop command type from history stack<br>        _undoCommandTypes.RemoveAt(_undoCommandTypes.Count - 1);    //remove undone command from history<br>        // <br><br>        _commandWrappers[commandType].Undo();   //ask wrapper of this command type to undo<br><br>        _redoCommandTypes.Push(commandType);    //push command in redo stack<br>    }<br><br>    public void Redo()<br>    {<br>        var commandType = _redoCommandTypes.Pop();<br><br>        _commandWrappers[commandType].Redo();<br><br>        AddToUndo(commandType);<br>    }<br><br>    private void ClearRedo()<br>    {<br>        _redoCommandTypes.Clear();<br>        _spawnCube.ClearRedo();<br>        _moveObject.ClearRedo();<br>    }<br><br>    //new <br>    private void AddToUndo(CommandType commandUndo)<br>    {<br>        if (_undoCommandTypes.Count + 1 &gt; _maxUndoCount)<br>        {<br>            //erase oldest element in history<br>            _commandWrappers[_undoCommandTypes[0]].EraseOldestHistoryEntry();<br>            _undoCommandTypes.RemoveAt(0);<br>        }<br>        _undoCommandTypes.Add(commandUndo);<br>    }<br>}</pre><p>This will allow commands to work as intended and don’t take too much additional memory space.</p><h4><strong>Additional</strong></h4><p>Be careful while using <strong>reference fields in arguments structs.</strong></p><p>References to unity objects (like GameObject, MonoBehaviours and other components) might be destroyed, and references to plain classes might reference old instances which will lead to unexpected behaviour (that’ll be hard to debug). This can easily happen while calling Undo/Redo.</p><p>Ultimate solution to this problem would be to use Data-Oriented design and accessing objects by some id. Or just be careful enough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b60cfcbd4e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Godot C# - Get child node by type <T> extension]]></title>
            <link>https://medium.com/@swiftroll3d/godot-c-getchildbytype-t-extension-186cd972ef78?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/186cd972ef78</guid>
            <category><![CDATA[godot]]></category>
            <category><![CDATA[getcomponent]]></category>
            <category><![CDATA[godot-4]]></category>
            <category><![CDATA[godot-engine]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 14:00:09 GMT</pubDate>
            <atom:updated>2023-09-23T13:58:19.192Z</atom:updated>
            <content:encoded><![CDATA[<p>This extension methods provides functionality similar to Unity’s GetComponentInChildren&lt;T&gt; or GetComponentInParent&lt;T&gt; without providing name or index of child (or iterating through multiple parents manually), it allows you to get node by type only</p><pre>using Godot;<br><br>public static class GDExtensions<br>{<br>    //acts like Unity&#39;s GetComponent&lt;T&gt; / GetComponentInChildren&lt;T&gt;<br>    public static T GetChildByType&lt;T&gt;(this Node node, bool recursive = true)<br>        where T : Node<br>    {<br>        int childCount = node.GetChildCount();<br><br>        for (int i = 0; i &lt; childCount; i++)<br>        {<br>            Node child = node.GetChild(i);<br>            if (child is T childT)<br>                return childT;<br><br>            if (recursive &amp;&amp; child.GetChildCount() &gt; 0)<br>            {<br>                T recursiveResult = child.GetChildByType&lt;T&gt;(true);<br>                if (recursiveResult != null)<br>                    return recursiveResult;<br>            }<br>        }<br><br>        return null;<br>    }<br><br>    //acts like Unity&#39;s GetComponentInParent&lt;T&gt;<br>    public static T GetParentByType&lt;T&gt;(this Node node)<br>        where T : Node<br>    {<br>        Node parent = node.GetParent();<br>        if (parent != null)<br>        {<br>            if (parent is T parentT)<br>            {<br>                return parentT;<br>            }<br>            else<br>            {<br>                return parent.GetParentByType&lt;T&gt;();<br>            }<br>        }<br><br>        return null;<br>    }<br>}</pre><p><em>Also at github gist:<br></em><a href="https://gist.github.com/swiftroll/8d933307b7e816e487f22f4e1e6e6e47"><em>https://gist.github.com/swiftroll/8d933307b7e816e487f22f4e1e6e6e47</em></a></p><p>Just copy this C# class in any place in your Godot project and you’ll be able to use it directly from nodes:</p><pre>public sealed partial class ExampleNode : Node<br> {<br>  public void Example()<br>  {<br>    SomeNodeType someNode = this.GetChildByType&lt;SomeNodeType&gt;();<br>  }<br> }</pre><p>Or like that:</p><pre>Node node = ...; <br>var someNodeType = node.GetChildByType&lt;SomeNodeType&gt;();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=186cd972ef78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickly migrating unit tests from Unity to Godot 4 C#]]></title>
            <link>https://medium.com/@swiftroll3d/quickly-migrating-unit-tests-from-unity-to-godot-4-c-d072c49d5631?source=rss-924a973c8941------2</link>
            <guid isPermaLink="false">https://medium.com/p/d072c49d5631</guid>
            <category><![CDATA[godot-engine]]></category>
            <category><![CDATA[godot-4]]></category>
            <category><![CDATA[godot]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[SwiftRoll ]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 18:35:14 GMT</pubDate>
            <atom:updated>2023-09-15T18:36:58.453Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need quickly to migrate your unit tests from Unity to Godot you can use code from this article</p><p>It’s not unit testing framework, just a code that allows running your tests almost without modifications.</p><p>I’d recommend rewriting your tests later to some fully working Godot unit testing framework, but right now it’s a bit of problem if you use C# and Godot 4, because frameworks like gdUnit4 and Gut don’t support this for now</p><p>Here’s how it’s going to look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2uKev9t7cCbB6SSlHlS8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1-wdifRMxsTwWeLasfRNA.png" /></figure><p><em>Whole code is available at </em><a href="https://github.com/swiftroll/UTests_UnityToGodot"><em>https://github.com/swiftroll/UTests_UnityToGodot</em></a></p><p><em>I wrote this code for my project that I migrate from Unity to Godot, so my skills with Godot are limited and feedback is greatly appreciated, I would like to learn if I done something wrong or just could do better. Thanks!</em></p><p><strong>Assertions</strong></p><p>First of all let’s write Assert functionality that looks like the one in Unity</p><pre>public static class Assert<br>{<br>  public static void IsTrue(bool val, string text = null)<br>  {<br>   Check(() =&gt; val, text);<br>  }<br><br>  public static void IsFalse(bool val, string text = null)<br>  {<br>   Check(() =&gt; !val, text);<br>  }<br><br>  public static void IsNull(object obj, string text = null)<br>  {<br>   Check(() =&gt; obj == null, text);<br>  }<br><br>  public static void IsNotNull(object obj, string text = null)<br>  {<br>   Check(() =&gt; obj != null, text);<br>  }<br><br>  private static void Check(Func&lt;bool&gt; func, string text)<br>  {<br>   if (text == null)<br>    text = &quot;Assertion failed&quot;;<br><br>   if (!func.Invoke())<br>   {<br>    GD.PrintErr($&quot;{text}&quot;);<br>    throw new AssertException(text);<br>   }<br>  }<br>}</pre><p>Also let’s add AssertException for this</p><pre>public sealed class AssertException : Exception<br>{<br>    public AssertException(string text) : base(text) { }<br>}</pre><p><strong>Attribute</strong></p><p>We’ll add attribute to identify test methods like in Unity. Here I call it UTest, but the name doesn’t matter. Here I’ll use one attribute for plain tests and coroutine tests</p><p>No code inside it is needed, it’s just for identification of methods</p><pre>public sealed class UTest : Attribute<br>{<br>}</pre><p><strong>Time</strong></p><p>For coroutine tests delta time is required. In Unity we have static access to it, let’s imitate that with UTestTime that we’ll update manually later</p><pre>public static class UTestTime<br>{<br>    public static double DeltaTime { get; set; }<br>}</pre><p><strong>Test runners (base)</strong></p><p>We’ll need two test runners — one for plain tests (that return void) and one for coroutine tests (the ones that return IEnumerator)</p><p>Both of these runners share some logics between them, so let’s start with the base class</p><pre>public abstract class UTestsRunnerBase<br>{<br>    protected readonly List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; _testMethods;<br><br>    protected int _currentIndex = 0;<br>    protected int _successfulNum = 0;<br>    protected int _failedNum = 0;<br><br>    public bool IsFinished =&gt; _currentIndex &gt;= _testMethods.Count;<br><br>    public UTestsRunnerBase(List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; testMethods)<br>    {<br>        _testMethods = testMethods;<br>    }<br><br>    public void Update()<br>    {<br>        if (IsFinished)<br>            return;<br><br>        //iterate through all test methods<br>        while (_currentIndex &lt; _testMethods.Count)<br>        {<br>            bool result = RunTest();<br>            if (!result)<br>                break;<br>        }<br>    }<br><br>    protected abstract bool RunTest();<br><br>    public abstract void LogResults();<br>}</pre><p><strong>Plain runner</strong></p><pre>public sealed class UTestsRunnerPlain  : UTestsRunnerBase<br>{<br>    public UTestsRunnerPlain(List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; testMethods) : base(testMethods) { }<br><br>    protected override bool RunTest()<br>    {<br>        var methodTuple = _testMethods[_currentIndex];<br>        GD.Print($&quot;-&quot;);<br>        GD.Print($&quot;Starting plain test: {methodTuple.Item1.GetType().Name}-&gt;{methodTuple.Item2.Name}&quot;);<br><br>        try<br>        {<br>            methodTuple.Item2.Invoke(methodTuple.Item1, null);<br>        }<br>        catch (Exception)<br>        {<br>            _failedNum++;<br>            _currentIndex++;<br>            GD.PrintErr($&quot;Failed plain test: {methodTuple.Item1.GetType().Name}-&gt;{methodTuple.Item2.Name}&quot;);<br>            throw;<br>        }<br><br>        _successfulNum++;<br>        _currentIndex++;<br>        GD.Print($&quot;Successful plain test: {methodTuple.Item1.GetType().Name}-&gt;{methodTuple.Item2.Name}&quot;);<br><br>        return true;<br>    }<br><br>    public override void LogResults()<br>    {<br>        GD.Print($&quot;{_testMethods.Count} plain tests have finished, successful:{_successfulNum}, failed:{_failedNum}&quot;);<br>    }<br>}</pre><p><strong>Coroutine runner</strong></p><pre>public sealed class UTestsRunnerCoroutine : UTestsRunnerBase<br>{<br>    private IEnumerator _currentCoroutine;<br>    private Tuple&lt;Node, MethodInfo&gt; _currentMethodTuple;<br><br>    public UTestsRunnerCoroutine(List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; testMethods) : base(testMethods) { }<br><br>    protected override bool RunTest()<br>    {<br>        if (_currentCoroutine == null)<br>        {<br>            _currentMethodTuple = _testMethods[_currentIndex];<br>            GD.Print($&quot;-&quot;);<br>            GD.Print($&quot;Starting coroutine test: {_currentMethodTuple.Item1.GetType().Name}-&gt;{_currentMethodTuple.Item2.Name}&quot;);<br><br>            _currentCoroutine = (IEnumerator)_currentMethodTuple.Item2.Invoke(_currentMethodTuple.Item1, null);<br>        }<br><br>        try<br>        {<br>            bool isRunning = _currentCoroutine.MoveNext();<br><br>            if (isRunning)<br>                return false;<br>        }<br>        catch (Exception)<br>        {<br>            _currentCoroutine = null;<br>            _failedNum++;<br>            _currentIndex++;<br>            GD.PrintErr($&quot;Failed coroutine test: {_currentMethodTuple.Item1.GetType().Name}-&gt;{_currentMethodTuple.Item2.Name}&quot;);<br>            throw;<br>        }<br><br>        _currentCoroutine = null;<br>        _successfulNum++;<br>        _currentIndex++;<br>        GD.Print($&quot;Successful coroutine test: {_currentMethodTuple.Item1.GetType().Name}-&gt;{_currentMethodTuple.Item2.Name}&quot;);<br><br>        return true;<br>    }<br><br>    public override void LogResults()<br>    {<br>        GD.Print($&quot;{_testMethods.Count} coroutine tests have finished, successful:{_successfulNum}, failed:{_failedNum}&quot;);<br>    }<br>}</pre><p><strong>Runner (controller)</strong></p><p>Here’s the tests controller that has links to actual tests and runs them</p><p>It collects test methods marked with UTest attribute by reflection from nodes listed at _testNodes</p><p>If method marked with attribute returns void, it’ll be plain test. If it return IEnumerator it’ll be coroutine test.</p><p>First it runs plain tests and only then coroutine tests.</p><pre>public sealed partial class UTestsRunner : Node<br>{<br> [Export] private Node[] _testNodes;<br> <br> private UTestsRunnerPlain _plain;<br> private UTestsRunnerCoroutine _coroutine;<br><br> private bool _isFinished;<br><br> public override void _Ready()<br> {<br>  Init(_testNodes.ToList());<br> }<br><br> public override void _Process(double delta)<br> {<br>  UTestTime.DeltaTime = delta;<br><br>  if (_isFinished)<br>   return;<br><br>  if (!_plain.IsFinished)<br>  {<br>   _plain.Update();<br>  }<br>  else if (_plain.IsFinished &amp;&amp; !_coroutine.IsFinished)<br>  {<br>   _coroutine.Update();<br>  }<br>  else if (_plain.IsFinished &amp;&amp; _coroutine.IsFinished)<br>  {<br>   GD.Print($&quot;---&quot;);<br>   _plain.LogResults();<br>   _coroutine.LogResults();<br>   _isFinished = true;<br>  }<br> }<br><br> private void Init(List&lt;Node&gt; nodes)<br> {<br>  List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; plainTestMethods = new();<br>  List&lt;Tuple&lt;Node, MethodInfo&gt;&gt; coroutineTestMethods = new();<br><br>  for (int i = 0; i &lt; nodes.Count; i++)<br>  {<br>   //find all methods with attribute<br>   var methodsPlain = nodes[i]<br>    .GetType()<br>    .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)<br>    .Where(m =&gt; m.GetCustomAttributes(typeof(UTest), false).Length &gt; 0)<br>    .Where(m =&gt; m.ReturnType == typeof(void));<br><br>   //add theem to list of plain methods<br>   foreach (var method in methodsPlain)<br>   {<br>    plainTestMethods.Add(new(nodes[i], method));<br>   }<br><br>   //find all methods with attribute<br>   var methodsCoroutine = nodes[i]<br>    .GetType()<br>    .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)<br>    .Where(m =&gt; m.GetCustomAttributes(typeof(UTest), false).Length &gt; 0)<br>    .Where(m =&gt; m.ReturnType == typeof(IEnumerator));<br><br>   //add theem to list of coroutine methods<br>   foreach (var method in methodsCoroutine)<br>   {<br>    coroutineTestMethods.Add(new(nodes[i], method));<br>   }<br>  }<br><br>  _plain = new(plainTestMethods);<br>  _coroutine = new(coroutineTestMethods);<br> }<br>}</pre><p><strong>Example tests</strong></p><p>You can put test scripts anywhere in project folder</p><pre>public sealed partial class UTestExample1 : Node<br>{<br>    [UTest]<br>    private void ExampleTest1()<br>    {<br>        Assert.IsTrue(1 == 1);<br>    }<br><br>    [UTest]<br>    private void ExampleTest2()<br>    {<br>        Assert.IsTrue(1 == 1);<br>        Assert.IsTrue(1 == 2, &quot;ExampleTest2 valid fail&quot;);<br>    }<br><br>    [UTest]<br>    private IEnumerator ExampleTest3()<br>    {<br>        Assert.IsTrue(1 == 1);<br><br>        yield break;<br>    }<br><br>    [UTest]<br>    private IEnumerator ExampleTest4()<br>    {<br>        double timer = 0f;<br>        while (timer &lt; 1f)<br>        {<br>            GD.Print($&quot;ExampleTest4 timer={timer}&quot;);<br>            timer += UTestTime.DeltaTime;<br>            yield return null;<br>        }    <br><br>        Assert.IsTrue(1 == 2, &quot;ExampleTest4 valid fail&quot;);<br><br>        yield break;<br>    }<br><br>    [UTest]<br>    private IEnumerator ExampleTest5()<br>    {<br>        GD.Print($&quot;ExampleTest5 waiting for user to press Space key&quot;);<br><br>        while (!Input.IsKeyPressed(Key.Space))<br>            yield return null;<br><br>        Assert.IsTrue(true);<br><br>        yield break;<br>    }<br>}</pre><p><strong>Scene and inspector setup in Godot editor</strong></p><ol><li>Add node that has UTestsRunner script</li><li>Add anywhere in the scene some nodes with scripts that have methods marked with [UTest]</li><li>In inspector of UTestsRunner add links to those nodes</li><li>Run play mode, see console and debugger for errors and tests statistics</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*gEd-H69B1N7ZdM08XUEN_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*N7I4mdUEa8g_mMnypHkBzQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d072c49d5631" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>